Recently I was having a discussion with a friend about Ruby's Proc
. You can call a Proc
in one of several ways. One way is to invoke Proc.call
:
p = Proc.new { |x| "hello, #{x}" }
p.call "Bob"
=> "hello, Bob"
Another is t开发者_如何学Pythono use braces, Proc.[]
:
p ["Bob"]
=> "hello, Bob"
Are there any potential precedence issues here, or are these two statements completely interchangeable? If not, can you provide an example of a context where different results would be provided?
The #call
technique allows the operator precedence to potentially obscure intent:
p = Proc::new do |a1| Proc::new do |a2| "#{a1.inspect}:#{a2.inspect}" end end
p.call([1,2,3]).call [1]
=> => "[1, 2, 3]:[1]"
p.call [1,2,3][1]
=> #<Proc:0x7ffa08dc@(irb):1>
p.call([1,2,3])[1]
=> "[1, 2, 3]:1"
p[[1,2,3]][[1]]
=> "[1, 2, 3]:[1]"
The []
syntax makes the syntactic association of the arguments to the method more robust, but you'd achieve the same effect by putting parentheses around the arguments to Proc#call
.
精彩评论