More & Tricks

Compare:


> def double(n)
>  n * 2
> end

> (1..5).map {|n| double(n)}
=> [2, 4, 6, 8, 10]

> (1..5).map &method(:double)
=> [2, 4, 6, 8, 10]

Explanation: method returns a Method object representing the named method. Method defines to_proc to return the Proc corresponding to the method. And we know that our trusty friend & tries to convert the object to a Proc using it’s to_proc method.

(via Giles Bowkett)