Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 1.8 and 1.9 string differences

Tags:

ruby

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

like image 660
Dennis Avatar asked Aug 03 '26 18:08

Dennis


2 Answers

Another solution

"string"[0].chr # => 's'
like image 130
intellidiot Avatar answered Aug 06 '26 11:08

intellidiot


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]
like image 24
DigitalRoss Avatar answered Aug 06 '26 11:08

DigitalRoss