Robin Winton
Robin Winton

Reputation: 601

Ruby send method to Array#map

I want to alter an array in ruby. Usually I'd do

[1,2,3].map{|i| i*3}

However I want to use send like I'd use to_s:

[1,2,3].map &:to_s

And I try this:

[1,2,3].map &:send(:*, 3)

but it returns an error

SyntaxError: unexpected '(', expecting $end
[1, 2, 3].map &:send(:*, 3)

How would I go about sending this block to map without using {}

Upvotes: 4

Views: 1008

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

In this particular case, you can exploit the fact that multiplication is (or at least should be) symmetric, i.e. that a*b == b*a:

[1, 2, 3].map(&3.method(:*))

Upvotes: 6

Related Questions