In Ruby on Rails development, I have been known to use symbol to proc. Recently, I needed to re-use a method as a block.
Here’s a contrived example of what I was doing:
Group.all.sort {|a,b| a.name <=> b.name}
However, I wanted to re-use this sort and ended-up refactoring it to:
def group_sort(a, b) a.name <=> b.name end Group.all.sort {|a,b| group_sort(a, b)}
Although this allowed me to re-use my sorting mechanism just fine, it seemed verbose. I was able to be succinct by using a lambda like so:
group_sort = lambda{|a,b| a.name <=> b.name} Group.all.sort &group_sort
(Using a lambda may be obvious to Ruby pros, but I’m not there yet.)