Are there any problems with Ruby priority using Proc.call vs. Proc. []?

I recently talked with a friend about Ruby Proc. You can call in Procone of several ways. One way is to call : Proc.call

p = Proc.new { |x| "hello, #{x}" }
p.call "Bob"
=> "hello, Bob"

Another is to use curly braces : Proc.[]

p ["Bob"]
=> "hello, Bob"

Are there any potential priority issues, or are these two statements completely interchangeable? If not, can you give an example of a context in which various results will be provided?

+3
source share
1 answer

The method #callallows operator priority to potentially hide 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]"

[] , , Proc#call.

+2

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


All Articles