Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use &: (ampersand colon) notation with a parameter or with chaining in Ruby? [duplicate]

Tags:

syntax

ruby

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'))

?

like image 688
Alexander Popov Avatar asked Nov 08 '13 10:11

Alexander Popov


1 Answers

: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))
                     ^
like image 186
Arup Rakshit Avatar answered Oct 01 '22 22:10

Arup Rakshit