K
K
Karina2017-08-26 14:55:00
Ruby on Rails
Karina, 2017-08-26 14:55:00

How to understand the construction of lambda and ampersand?

there is such a code

decorator = -> (item) do
  # действия с item
end
[array].select(& ->(item) { item[:auth] }).map(&decorator)

I understand that this construction
[array].select(& ->(item) { item[:auth] }).map(&decorator)

is equivalent to this one
[array].select{|item|  item[:auth] }.map(&decoration)

but I can't figure out why.
Specifically, I don’t understand this code, I don’t understand - why is the & sign here? It is relevant only here - map(&decoration), because we pass lambda to the function Thank you all for your answers
& ->(item) { item[:auth] }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitri Sinitsa, 2017-08-26
@iKapex

decorator is an object of type Proc (lambda, but not the gist). An ampersand before an object of type Proc turns it into a block, which is NOT an object and cannot be instantiated in any way. If an ampersand is in front of an object that is NOT of type Proc, then it first tries to call on it a method called "to_proc", which specifies the logic for turning the object into an object of type Proc, which in turn will be converted to block (example - Symbol, map(&:to_i))
"#select" and "#map" expect block as input

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question