«

&: in Ruby

As a new ruby developer, I’m constantly surprised by the little shortcuts and niceties of the language.

One technique I often see is to pass &:symbol into an enumerable method, where :symbol is a method on the object.

For example:

animals = %w[dog cat mouse]
animals.map &:upcase
=> ["DOG", "CAT", "MOUSE"]

Behind the scenes, this is translating the :upcase symbol into a Proc and passing it into the map method which will run the Proc on each element in the enumberable.

The above code is equivalent to:

animals = %w[dog cat mouse]
animals.map { |animal| animal.upcase }
=> ["DOG", "CAT", "MOUSE"]

There are slight performance gains by writing the block explicitly, but I think the conciseness of the &:symbol trick is worth the slight hit.

Edit: As further proof of my theory that RailsCasts provides all you need to know about Ruby and Rails, this trick was covered waaaay back in Episode 6

Share Comment on Twitter