Magic of Ruby &
Ruby has the syntax feature like &
with many use scenario. I combined some interesting posts I have found.
Let’s start from the basics. Ruby has the following syntax feature:
collection.map(&:name)
which means
collection.map{ |el| el.name }
It works because Ruby expands &:name
to &:name.to_proc
and adds method to_proc for the Symbol class
class Symbol
def to_proc
Proc.new do |obj, *args|
obj.send self, *args
end
end
end
Consequences
The &
operator may take any proc object or the objects that can be converted to proc by to_proc method.
inc = proc { |e| e + 1 }
collection.map(&inc)
You can use the self’s methods
collection.map(&method(:foo))
# ==
collection.map{ |el| foo(el) }
Parameters
You can supply arguments to &
syntax too. (ref [2])
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
alias call with
end
a = [1,3,5,7,9]
a.map(&:+.with(2))
# or
a.map(&:+.(2))
# [3, 5, 7, 9, 11]
As we saw above the proc
object could be taken from the method of an instance so for the simple arithmetic this works too.
a = [1,3,5,7,9]
a.map(&2.method(:+))
# [3, 5, 7, 9, 11]
a.map(&2.method(:*))
# [2, 6, 10, 14, 18]
Reference links
Compiled from the following posts