views:

65

answers:

1

Somewhere i saw a way to simplify ruby blocks with one argument, it basically omitted vertical bars and argument declaration, because it was somehow inlined. I cannot find it anymore or remember any names t osearch for. Can you help?

+6  A: 

There is a simplifications that works in a few situations.

If you have something like:

(1..10).collect { |i| i.to_s }

You can simplify it to:

(1..10).collect(&:to_s)

The & converts the symbol to a proc by calling Symbol#to_proc. It doesn't work with additional arguments, and it only works if you want to invoke a method directly on the block argument. It was introduced in Rails (ActiveSupport), but made its way into core Ruby 1.8.7 and 1.9.

molf