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.
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs