Ruby - Symbol to_proc - A shortcut for the map/collect method
instead of this:
list = %w[a b c d e f snag]
p list.map {|el| el.capitalize }
#=> [“A”, “B”, “C”, “D”, “E”, “F”, “Snag”]
you can save yourself some typing:
list = %w[a b c d e f snag]
p list.map(&:capitalize)
# or even
p list.map &:capitalize # since parentheses are optional in ruby
#=> [“A”, “B”, “C”, “D”, “E”, “F”, “Snag”]
Explanation…
.map
, .each
, and similar methods expect a block. A block is usually denoted by curly braces with a method inside.
-
The colon before the method name is just how you refer to methods in ruby. You pass its name around as a symbol.
-
The ampersand, in this case, is the shorthand for converting a proc to a block.*
-
Your method symbol, however is not yet a proc, so it converts itself into a proc using the symbol object’s own internal
.to_proc
method. -
Then ampersand then turns it into a block and
.map
happily inserts all the elements of the collection into the block one by one, just as before.
Here are a few more examples.
projects.any? &:valid?
projects.each &:save!
And finally, this technique is mainly useful when chaining together methods.
projects.collect(&:name).collect(&:downcase)
*if you don’t know what blocks, procs and lambdas are, CodeSchool’s RubyBits 1 and 2 courses are good places to start.