2

What is the difference between using & in these two cases?

  1. Calling fun1:

    fun1(&toproc)
    
  2. In function definition:

    def fun1(&toblock)
      # ...
    end
    

Is it that when receiving a parameter with &toblock it is converted to a Proc and for the other case it is converted to a block?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
new user20
  • 59
  • 4
  • Not quite a duplicate, but the answers to this question answer your question: http://stackoverflow.com/questions/28439734/purpose-of-ampersand-in-ruby-for-procs-and-calling-methods – Dave Schweisguth May 24 '16 at 21:53

1 Answers1

3

In the first case, toproc is a variable which contains a proc, or will be cast to a proc if not.

In the second case, we are explicitly declaring that the function takes a block argument, which we can refer to by the name toblock.

This article gives a pretty good explanation: http://www.skorks.com/2013/04/ruby-ampersand-parameter-demystified/

Fred Willmore
  • 4,386
  • 1
  • 27
  • 36