Is it possible to use the &: (ampersand) colon notation with a parameter or with a chain in Ruby?

I want to do something like:

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

In addition, how can you do something similar to:

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

?

+6
source share
2 answers

:to_s is a symbol, not a method. Therefore, you cannot pass any arguments, for example :to_s(2) . If you do, you will receive an error message. How your code will not work. Thus, [1, 2, 3].map(&:to_s(2)) impossible, where possible [1, 2, 3].map(&:to_s) . &:to_s means that you call the #to_proc method on a character. Now in your case &:to_s(2) means :to_s(2).to_proc . Error before calling the #to_proc method.

 :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 own and compare the error with the above explanation:

 [1, 2, 3].map(&:to_s(2)) syntax error, unexpected '(', expecting ')' [1, 2, 3].map(&:to_s(2)) ^ 
+4
source

If you don't need dynamic parameters, you can do something like this:

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

And for your second example, this would be:

 to_sr = Proc.new {|a| a.to_s(2).rjust(8, '0')} [1, 2, 3].map &to_sr 
+4
source

Source: https://habr.com/ru/post/957663/


All Articles