문제

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 to 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top