Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the functionality of "&: " operator in ruby? [duplicate]

Tags:

ruby

Possible Duplicate:
What does map(&:name) mean in Ruby?

I came across a code snippet which had the following

a.each_slice(2).map(&:reverse) 

I do not know the functionality of &: operator. How does that work?

like image 365
Rahul Avatar asked Feb 24 '12 11:02

Rahul


People also ask

What does functionality of an app mean?

functionality. In information technology, functionality (from Latin functio meaning "to perform") is the sum or any aspect of what a product, such as a software application or computing device, can do for a user.

What is functionality of a system?

Functionality is the ability of the system to do the work for which it was intended.

What is called functionality?

Britannica Dictionary definition of FUNCTIONALITY. 1. [noncount] : the quality of having a practical use : the quality of being functional. a design that is admired both for its beauty and for its functionality.

What does functionality of a product mean?

A product's functionality is used by marketers to identify product features and enables a user to have a set of capabilities. Functionality may or may not be easy to use. Also see function.


2 Answers

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) 
like image 102
Gareth Avatar answered Oct 18 '22 09:10

Gareth


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 } 
like image 28
KL-7 Avatar answered Oct 18 '22 09:10

KL-7