Dennis
Dennis

Reputation: 410

Ruby 1.8 and 1.9 string differences

How can I get the first character of a string that works both in ruby 1.8 (bytes) and 1.9 (characters)?

Upvotes: 2

Views: 423

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146073

This should do it...

s[0,1]

This returns the first byte in 1.8 and the first character in 1.9, but in each case the result is a String.

If you want the first UTF-8 character sequence in both, it's tricky. The regex engine is one place in 1.8 with UTF-8 awareness, so you could use:

s[/./u]

Upvotes: 5

intellidiot
intellidiot

Reputation: 11228

Another solution

"string"[0].chr # => 's'

Upvotes: 5

Related Questions