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}"]
end
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}
end
end end
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 end
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.
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.