Kyle Decot Kyle Decot - 4 months ago 17
Ruby Question

String#[] Differences between Ruby 1.8.7 and 1.9.3

I'm attempting to upgrade an old rails 2.x/ruby 1.8.7 application but I'm
running into an issue. I have the string

\200\001\002\004\b\020
and in my code
I have something that looks like:

"\200\001\002\004\b\020"[0]


In 1.8.7 this returns the Fixnum
128
. In ruby 1.9.3 (and newer) however this
returns the String
\x80
.

My question is two part: First, what's happening here, and secondly how can I
get a similar behavior to what's being returned in 1.8.7 in newer versions of
ruby?

Update #1



As some have suggested I tried
"\200\001\002\004\b\020".bytes[0]
but this however doesn't work (it does work in
2.3.1
though) as it errors with:

NoMethodError: undefined method `[]' for #<Enumerator: "\x80\u0001\u0002\u0004\b\u0010":bytes>

Answer

To get the old behavior, use String#getbyte, as in:

"\200\001\002\004\b\020".getbyte(0)