Hommer Smith
Hommer Smith

Reputation: 27862

How to use &:symbol notation with map and a custom method?

I have the following code:

def add_one(el)
  el += 1
end

p [1,2,3].map { |el| add_one(el) }
p [1,2,3].map(&:add_one)

When I try the &:add_one, I get map: private method add_one called for 1:Fixnum (NoMethodError)

What am I missing here? How can I call add_one with the &: notation?

Upvotes: 1

Views: 82

Answers (3)

Uri Agassi
Uri Agassi

Reputation: 37419

Actually, you can do something similar to &: for a method on self using the method method:

def add_one(el)
  el += 1
end

p [1,2,3].map(&method(:add_one))
# [2, 3, 4]

Upvotes: 1

Oleh  Sobchuk
Oleh Sobchuk

Reputation: 3722

If you have Active Record relation for example for User with fields :name, :age, :address you can use it:

users = User.all

so you can use &:...

users.map(&:name) # => ['John', 'Oleg', 'Egor']

same

users.map { |user| user.name }

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187232

The & notation that converts a symbol to a proc doesn't work like that. It creates a block where the argument passed to it is the receiver of the method call, not the argument.

p [1,2,3].map(&:add_one)
# is equivalent to this
p [1,2,3].map { |el| el.add_one }

How can I call add_one with the &: notation?

You don't. You simply wouldn't use the shorthand form in this case. There's no reason to.

Upvotes: 2

Related Questions