String#each missing in ruby1.9

One might have noticed that String#each is no more present in ruby1.9

1.9.1 :002 > "hemanth".each
NoMethodError: undefined method `each' for "hemanth":String

Lately, was working on huge code base where, code had String#each assuming it will always get an array as ruby1.8 has String#each and also Array#each, but it does not get Strings at times so had to fix them.

Methods to fix :

  • Check and cast :

if !obj.kind_of?(Array)
      acl_descs = ["#{obj}"]

This was bit tedious, some 'sed' could have helped, but stopped it there!

  • Check and Create :

unless String.respond_to?(:each)
  class String
    def each
      self.split.each {|line| yield line}

This was worth doing, but was in search of an easier way!

  • Aliasing for the win!

String#each_line is the method that helped a lot, as it was present in both 1.8 and 1.9.

class String 
   alias :each :each_line

Finally, removal of String#each from 1.9 is really meaningful, as it was ugly string.each {|each_what???|

So, ruby 1.9 along with each_line has each_word and each_char.

Share this