Monday, March 10, 2008

Quick Tip - to_proc

We all know that & (ampersand) is used to denote a block variable but what you may not know is that Rails ActiveSupport (and soon to be in ruby 1.9) has a nice extension on Symbol that can make use of this convention by adding a to_proc method.

For example instead of:

["This", "blog", "is", "great"].map {|w| w.upcase}
=> ["THIS", "BLOG", "IS", "GREAT"]

We could simplify it by:

["This", "blog", "is", "great"].map(&:upcase)
=> ["THIS", "BLOG", "IS", "GREAT"]

What ruby ends up do is calling the to_proc method on that symbol and it coerces into a block!

Here is a link to the documentation and for those who are lazy I have posted the source below.

# File lib/extensions/symbol.rb, line 23
def to_proc
proc { |obj, *args| obj.send(self, *args) }

No comments: