Handling Ruby’s String.each_char Iterator
2008-06-25Ahh the joys of iterators. I can't say enough about how much they make my life easier. They are just so darn handy. Life was good in my Ruby world until I needed to iterate through the characters in a string. Thinking to myself, "there has got to be a method that does this," I looked up Ruby's String class and saw just what the doctor ordered… each_char.
Feeling pretty proud that my favorite language had this baked right in, I was only to happy to inject it into my code and test it out. That is until I recieved the dreaded NoMethodError: undefined method 'each_char' . Eeek, what did I do wrong? Did I mispell the method…..Nope, did I call it correctly…..Yep. Well, what the heck is going on?
After multiple attempts to find the answer on Google, I finally posted my problem to the ruby-talk group. I was told that the Ruby 1.8 String implementation that I was using only understood bytes and that I could use require 'jcode' to get the iterator to work the way I wanted. I did some looking around and I am not sure this is a great solution, after all, I could have easily used the each_byte{|f| f.chr} to iterate through and convert accordingly. I don’t understand why something that is documented as part of the class, does not work.
It would really help if there was an easy to search area on the net dedicated to language quirks for people trying to get a better grasp of their programming language of choice. Maybe that will be my next ROR project.
As it turns out, my Ruby 1.8.7 installation on my Fedora core 9 works as advertised.