views:

66

answers:

1

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?

+2  A: 

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.

Aidan Cully
Hmm... that's not quite what I'm after. This shows a difference between `.call(x).call` and `.call x.call`, not `.call` and `[]`.
John Feminella
@John Feminella, try `p["John"]["Barry"]` to see the difference. Perhaps Aidan will want to add that to his answer.
Wayne Conrad
@Wayne Conrad - Thanks - I've incorporated a new example based on that.
Aidan Cully
This example's much clearer and definitely does show a difference. Thanks, Aidan and Wayne!
John Feminella