psantos psantos - 1 year ago 73
Ruby Question

Ruby Procs - ends up with syntax error

Trying to understand Procs on Ruby, and for this I am trying some exercices.

First I type this line

[1, 4, 5, 3].map(&:anything)

And as a result I got an error:

NoMethodError: undefined method
anything' for 1:Fixnum

Then I try this one:

[1, 4, 5, 3].map(&:to_s)

And a new array with the numbers transformed to string was returned:

=> ["1", "4", "5", "3"]`.

With those two examples, I can conclude that, when I call something like:
[1, 4, 5, 3].map(&:anything)
method is called for each element in the array. And because a Fixnum don't implement the
method, the first example ends with error and the second passed.

Then I think, if Fixnum have a
method, then I can call
[1, 4, 5, 3].map(&:+2)
. But this ends with a syntax error:

syntax error, unexpected tINTEGER, expecting ')' [1, 4, 5, 3].map(&:+2)

why this last is giving me this syntax error if a Fixum have a
method ? What I am doing wrong?

Answer Source

& is a shortcut for calling the to_proc method. Because you have a symbol (:anything) the to_proc method is called on the symbol. This returns a proc which will call the method with the corresponding name (anything) on the object that is passed as argument.

If you do this with an enumerator like map then you actually call the method on each object in the collection.

Now this shortcut does not allow you to pass an argument to the methods. (+ is just syntactic sugar for calling a method on a number that takes another method as argument)

But you can use currying for such a use case:

add = -> (a, b) { a + b }
add_two =

p [1,2,3,4].map(&add_two) # => [3, 4, 5, 6]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download