问题描述
我想做类似的事情:
[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'))
?
推荐答案
:to_s
是一个符号,而不是一个方法.所以你不能像 :to_s(2)
那样传递任何参数给它.如果你这样做,你会得到错误.这就是你的代码无法工作的方式.所以 [1, 2, 3].map(&:to_s(2))
是不可能的,其中因为 [1, 2, 3].map(&:to_s)
可能.&:to_s
表示您正在调用 #to_proc
方法在符号上.现在在您的情况下 &:to_s(2)
表示 :to_s(2).to_proc
.调用方法#to_proc
之前会发生错误.
: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))
^
这篇关于是否可以将 &:(与号)符号与参数或 Ruby 中的链接一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!