Enumerable makes me giddy
I’ve been obsessing over the wonders of the Enumerable Module in Ruby for a little while now.
One of the first Ruby bits that I ever learned (but didn’t really grasp until recently) was using each() as a better iterator.@books.each { |book| book.read }which is more elegant than
for book in @books book.read endonce you understand and become |one| with the block. Thats nice, but it wasn’t until I caught wind of the other Enumerable methods that my mind was blown.
I have a particular fondness for inject()
Building a space-delimited list of tags from an array of tags could be a relative clunk fest. Iterating over an array and adding the tags to the total list. My initial code was something like:def tag_list list = "" tags.each do |skill| list += skill.name + " " end list.strip endThats not so bad. But something as simple as that should be able to fit on one line
def tag_list tag.inject("") {|list,tag| list + tag.name + " " }.strip endinject() is a great tool once you realize the power of the shortcut. That goes for all the methods of Enumerable. The shortcuts are all based on the same idea of iterating over a collection and executing a block. The difference is what is returned out of the block and how the result is handled. For example, any?() iterates over a collection passing each element to a block and asserting whether the block returns true. If any block pass returns true, the function returns true.
The power of many of the Enumerable functions have been ported to JavaScript via the Prototype library. I’d say it should be brought to PHP, too, but that’s usually where the elegance train stops.