views:

155

answers:

2

I am working with ruby 1.8.6 (2007-03-13 patchlevel 0) [x86_64-linux] and I get

undefined method `bytes' for #<String:0x2a95ec2268> (NoMethodError)

even though my code works on ruby 1.8.7. patchlevel 249 I saw somewhere that you need to add require "jcode" for a similar method not defined error with each_byte. I tried adding that but it still does not work. Any suggestions are very appreciated.

+2  A: 

Ruby 1.8.6 doesn't have String#bytes. That's a 1.9 addition that was backported to 1.8.7.

You can roughly implement it yourself like this:

class String
  require 'enumerator'

  def bytes(&block)
    return to_enum(:each_byte) unless block_given?
    each_byte &block
  end
end unless ''.respond_to?(:bytes)

[Note: I haven't checked whether this actually fulfills the contract of String#bytes 100%, but it is close enough for my use.]

Jörg W Mittag
Thanks for your answer. I noticed something interesting though.When I run `mystr.bytes.inject{|x, y|(x << 8) | y}` I get a fixnum, but when I run with the code your snippet I get a string object.
artsince
Jörg W Mittag
+1  A: 

In Ruby 1.8.6, you can:

require 'backports'

Ta-da, you now have access to String#bytes.

You also have all the many other changes introduced in 1.8.7. And most of 1.9.1, and all of the upcoming 1.9.2...

Marc-André Lafortune
I get no such file to load error when I add that statement.
artsince
You'll need to install it, like other gems, with `sudo install backports`
Marc-André Lafortune
I see, I might not be able to do this as I am trying to run a cron job on my paid hosting account
artsince
You should be able to install gems on any hosting account. Gems are fundamental to Ruby; almost all libraries are packaged this way. You might have to do `install backports` (without the sudo) instead though.
Marc-André Lafortune