Saturday, January 1, 2011

Shorthand anonymous functions in Ruby

In Scala, the anonymous function (n) => n * 2 can be shortened to _ * 2, which can be handy when dealing with only one or two arguments. Why don't we try this in Ruby :)
class Symbol
  def method_missing(name, *args)
    lambda { |n| n.send(name, *args) }
  end
end

puts (1..10).map &:n * 2
puts (1..10).map { |n| n * 2 }
puts (1..10).map &lambda { |n| n * 2 }
If you're not familiar with Ruby, the "&" turns the argument into a block - which is usually passed in with block syntax such as { |n| n * 2 }.