Search code examples
rubylambdasyntaxproc

What does it mean by prefixing a & to a raw proc object (not lambda) in Ruby?


I'm using Ruby 2.5 for testing. I have the following code.

p = proc {|e| puts e}

def test &b
    b.call 1 if block_given?
end

test &p

The output is:

1

&b will make the variable b catch the passed in block. But in the demo, I don't have a block. What I have is a raw proc object (not lambda). It seems &p converts the proc object back to a block, just as I write test {|e| puts e}. Is this ture? What does & do here?


Solution

  • What does & do here?

    Exactly that, convert proc to a block.

    I don't have a block. What I have is a raw proc object (not lambda)

    Do you perhaps think these (proc and lambda) are two completely different entities? They're not. They're almost the same thing.

    proc {} # => #<Proc:0x00007fe50882ecc8@-:1>
    -> {} # => #<Proc:0x00007fe50882e840@-:2 (lambda)>
    

    Certainly the same thing as far as & operator is concerned.