Finbarr
Finbarr

Reputation: 32126

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 I can safely write the code above to produce 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 clever.

Upvotes: 3

Views: 324

Answers (4)

Mark Reed
Mark Reed

Reputation: 95252

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"

Though of course it depends on your encoding.

Upvotes: 0

Mark Reed
Mark Reed

Reputation: 95252

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

"abc"[0,1]

Upvotes: 5

AShelly
AShelly

Reputation: 35540

"abc"[0].chr

produces the 2nd 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

Upvotes: 5

Simon
Simon

Reputation: 629

What about "abc"[0].ord ?

http://ruby-doc.org/core-1.9.3/String.html#method-i-ord

Upvotes: -1

Related Questions