11

I want to do something like:

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

Also, how can one do something similar to:

[1, 2, 3].map(&:to_s(2).rjust(8, '0'))

?

Alexander Popov
  • 23,073
  • 19
  • 91
  • 130
  • 1
    http://stackoverflow.com/questions/9932678/how-do-you-pass-an-argument-to-ruby-array-map-short-cut – tokland Nov 08 '13 at 10:21

2 Answers2

7

:to_s is a symbol,not a method. So you can't pass any argument to it like :to_s(2). If you do so,you will get error.That's how your code wouldn't work.So [1, 2, 3].map(&:to_s(2)) is not possible,where as [1, 2, 3].map(&:to_s) possible.&:to_s means you are calling #to_proc method on the symbol. Now in your case &:to_s(2) means :to_s(2).to_proc. Error will be happened before the call to the method #to_proc.

:to_s.to_proc # => #<Proc:0x20e4178>
:to_s(2).to_proc # if you try and the error as below

syntax error, unexpected '(', expecting $end
p :to_s(2).to_proc
       ^

Now try your one and compare the error with above explanation :

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

syntax error, unexpected '(', expecting ')'
[1, 2, 3].map(&:to_s(2))
                     ^
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
7

If you don't need the parameters to be dynamic you could do something like this:

to_s2 = Proc.new {|a| a.to_s(2)}
[1, 2, 3].map &to_s2

And for your second example it would be:

to_sr = Proc.new {|a| a.to_s(2).rjust(8, '0')}
[1, 2, 3].map &to_sr
David
  • 7,310
  • 6
  • 41
  • 63