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?
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?
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)
salary
for example –
Stayathome 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 }
© 2022 - 2024 — McMap. All rights reserved.
map(&:name)
mean in Ruby?, What exactly is&:capitalize
in Ruby?, Ruby/Ruby on Rails ampersand colon shortcut, Ruby :&:symbol
syntax, … – Jerz&:last
Ruby Construct Called?, What do you call the&:
operator in Ruby?, What doesmap(&:name)
do in this Ruby code?, What are:+
and&+
in ruby?,&:views_count
inPost.published.collect(&:views_count)
, Ruby Proc Syntax, How does “(1..4).inject(&:+)
” work in Ruby, … – Jerz&:property
?, What does the&
mean in the following ruby syntax?, Why would one use the unary operator on a property in ruby? i.e&:first
, how doesArray#map
have parameter to do something like this?, and what does&:
mean in ruby, is it a block mixed with a symbol?. – Jerz