65 Ruby 1.9 * "abc"[0] => "a" Is there a way that...">

Ruby 1.8.7 vs 1.9 * String [Fixnum] differences

Ruby 1.8.7:

"abc"[0]
=> 65

      

Ruby 1.9 *

"abc"[0]
=> "a"

      

Is there a way that I can safely write the code above to get the second result in both 1.8.7 and 1.9 *? My solution so far is: "abc".split('').first

but that doesn't seem very smart.

+3


source to share


4 answers


"abc"[0].chr

      

gives the second result in both versions.



1.8: http://ruby-doc.org/core-1.8.7/Integer.html#method-i-chr
1.9: http://ruby-doc.org/core-1.9.3/String.html#method -i-chr

+5


source


If you want the first character of a string as a string, then add the length in parentheses:



"abc" [0,1]

+5


source


Note that in 1.8 most of these answers will only work for characters in the ASCII range:

irb(main):001:0>  "ā"[0].chr
=> "\304"
irb(main):002:0>  "ā"[0,1]
=> "\304"
irb(main):003:0>  "ā"[0..0]
=> "\304"

      

Although of course it depends on your encoding.

0


source


-1


source







All Articles