Ruby each_char in String Class Broken

Thursday, January 1, 2009
A quick tech tip... Ruby's String.each_char() method doesn't work in 1.8 because of Unicoding issues (Ruby isn't very Unicode-savvy yet).

But for those of us who ever might need to iterate over a String in an app that doesn't use or need Unicode, it's surprisingly hard to find a simple workaround to this stupid little problem!

Here's an easy workaround:

mystring = 'hello'
mystring.each_byte {|b|
c = b.chr
}
### variable c now contains the character
### you'd expect from each_char() if it worked

And Ruby being the rather agreeable language that it is, you can even just patch this fix into the String class itself:

class String
def each_char()
each_byte {|b|
yield b.chr
}
end
end

Just require whatever file you put that patch in and you're back in business to use String.each_char() normally.

Sounds dumb, but I spent 1/2 an hour figuring out this simple solution. So I hope I've saved you 1/2 an hour today, and I hope you "pay it forward" to the world and do something good with that extra time...

Comments