Higher Order Messages for Mapping
Posted by Trejkaz Thu, 03 Nov 2005 23:29:00 GMT
Say you want to convert an array of strings to uppercase. You could write
result = names.map { |name| name.upcase }
PragDave suggests an alternative which uses the Ruby Extensions Project’s Symbol#to_proc method to pass a symbol.
result = names.map(&:upcase)
This is all well and good, but can you really call it elegant? Suppose you want to add 1 to all elements in a list. How can this method let you pass in that parameter? It seems that it can’t.
Higher Order Messages (HOM) provide a better way, although a way which seems even more like magic.
The Homer project offers HOM for Ruby, and although it didn’t have a method which did something like map, it was relatively simple to whip something together.
My own version of the above functionality:
result = names.map_using.upcase
Isn’t that better? I couldn’t call it map without causing a little mayhem, having to alias the old version and still provide complete compatibility was a bit much for me at this point in time.
But better yet, this version does permit you to use parameters:
costs_with_gst = costs.map_using * 1.1
Don’t bother asking for the source code for this… I’ll be shuffling it up to the Homer project as soon as I hit submit. ;-)