what is the functionality of "&: " operator in ruby? [duplicate]
Asked Answered
T
126

There isn't a &: operator in Ruby. What you are seeing is the & operator applied to a :symbol.

In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.

my_proc = Proc.new { puts "foo" }

my_method_call(&my_proc) # is identical to:
my_method_call { puts "foo" }

So the question now becomes "What does Symbol#to_proc do?", and that's easy to see in the Rails documentation:

Turns the symbol into a simple proc, which is especially useful for enumerations. Examples:

# The same as people.collect { |p| p.name }
people.collect(&:name)

# The same as people.select { |p| p.manager? }.collect { |p| p.salary }
people.select(&:manager?).collect(&:salary)
Twelfthtide answered 24/2, 2012 at 11:27 Comment(3)
@kikito: ruby-doc.org/core-1.9.3/Symbol.html#method-i-to_procMeadowsweet
@kikito: actually it was first implemented in Rails, but everyone loved it so it made its way into the core.Meadowsweet
Is there a way to pass and argument to the method being called? salary for exampleStayathome
T
41

By prepending & to a symbol you are creating a lambda function that will call method with a name of that symbol on the object you pass into this function. Taking that into account:

ar.map(&:reverse)

is roughly equivalent to:

ar.map { |element| element.reverse }
Tactile answered 24/2, 2012 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.