<p>In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and <code>Proc.new</code> on the other. </p>

<ul>
<li>What are those differences?</li>
<li>Can you give guidelines on how to decide which one to choose?</li>
<li>In Ruby 1.9, proc and lambda are different. What's the deal?</li>
</ul>

[{'answer_id': 629, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 5, 'selected': False, 'text': '<p>I found <a href="http://raulparolari.com/Ruby2/lambda_Proc" rel="noreferrer">this page</a> which shows what the difference between <code>Proc.new</code> and <code>lambda</code> are.  According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas <code>Proc.new</code> converts missing arguments to <code>nil</code>.  Here is an example IRB session illustrating the difference:</p>\n\n<pre>irb(main):001:0> l = lambda { |x, y| x + y }\n=> #&lt;Proc:0x00007fc605ec0748@(irb):1&gt;\nirb(main):002:0> p = Proc.new { |x, y| x + y }\n=> #&lt;Proc:0x00007fc605ea8698@(irb):2&gt;\nirb(main):003:0> l.call "hello", "world"\n=> "helloworld"\nirb(main):004:0> p.call "hello", "world"\n=> "helloworld"\nirb(main):005:0> l.call "hello"\nArgumentError: wrong number of arguments (1 for 2)\n    from (irb):1\n    from (irb):5:in `call\'\n    from (irb):5\n    from :0\nirb(main):006:0> p.call "hello"\nTypeError: can\'t convert nil into String\n    from (irb):2:in `+\'\n    from (irb):2\n    from (irb):6:in `call\'\n    from (irb):6\n    from :0</pre>\n\n<p>The page also recommends using lambda unless you specifically want the error tolerant behavior.  I agree with this sentiment.  Using a lambda seems a tad more concise, and with such an insignificant difference, it seems the better choice in the average situation.</p>\n\n<p>As for Ruby 1.9, sorry, I haven\'t looked into 1.9 yet, but I don\'t imagine they would change it all that much (don\'t take my word for it though, it seems you have heard of some changes, so I am probably wrong there).</p>\n'}, {'answer_id': 723, 'author': 'Joey deVilla', 'author_id': 216, 'author_profile': 'https://Stackoverflow.com/users/216', 'pm_score': 10, 'selected': True, 'text': '<p>Another important but subtle difference between procs created with <code>lambda</code> and procs created with <code>Proc.new</code> is how they handle the <code>return</code> statement:</p>\n\n<ul>\n<li>In a <code>lambda</code>-created proc, the <code>return</code> statement returns only from the proc itself</li>\n<li>In a <code>Proc.new</code>-created proc, the <code>return</code> statement is a little more surprising: it returns control not just from the proc, <strong>but also from the method enclosing the proc!</strong></li>\n</ul>\n\n<p>Here\'s <code>lambda</code>-created proc\'s <code>return</code> in action. It behaves in a way that you probably expect:</p>\n\n<pre><code>def whowouldwin\n\n  mylambda = lambda {return "Freddy"}\n  mylambda.call\n\n  # mylambda gets called and returns "Freddy", and execution\n  # continues on the next line\n\n  return "Jason"\n\nend\n\n\nwhowouldwin\n#=&gt; "Jason"\n</code></pre>\n\n<p>Now here\'s a <code>Proc.new</code>-created proc\'s <code>return</code> doing the same thing. You\'re about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:</p>\n\n<pre><code>def whowouldwin2\n\n  myproc = Proc.new {return "Freddy"}\n  myproc.call\n\n  # myproc gets called and returns "Freddy", \n  # but also returns control from whowhouldwin2!\n  # The line below *never* gets executed.\n\n  return "Jason"\n\nend\n\n\nwhowouldwin2         \n#=&gt; "Freddy"\n</code></pre>\n\n<p>Thanks to this surprising behavior (as well as less typing), I tend to favor using <code>lambda</code> over <code>Proc.new</code> when making procs.</p>\n'}, {'answer_id': 7484, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 1, 'selected': False, 'text': "<p>The difference in behaviour with <code>return</code> is IMHO the most important difference between the 2. I also prefer lambda because it's less typing than Proc.new :-)</p>\n"}, {'answer_id': 32329, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://innig.net/software/ruby/closures-in-ruby.html" rel="nofollow noreferrer">Closures in Ruby</a> is a good overview for how blocks, lambda and proc work in Ruby, with Ruby. </p>\n'}, {'answer_id': 48054, 'author': 'Peeja', 'author_id': 4937, 'author_profile': 'https://Stackoverflow.com/users/4937', 'pm_score': 2, 'selected': False, 'text': "<p>To elaborate on Accordion Guy's response:</p>\n\n<p>Notice that <code>Proc.new</code> creates a proc out by being passed a block.  I believe that <code>lambda {...}</code> is parsed as a sort of literal, rather than a method call which passes a block.  <code>return</code>ing from inside a block attached to a method call will return from the method, not the block, and the <code>Proc.new</code> case is an example of this at play.</p>\n\n<p>(This is 1.8.  I don't know how this translates to 1.9.)</p>\n"}, {'answer_id': 55491, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Proc is older, but the semantics of return are highly counterintuitive to me (at least when I was learning the language) because:</p>\n\n<ol>\n<li>If you are using proc, you are most likely using some kind of functional paradigm. </li>\n<li>Proc can return out of the enclosing scope (see previous responses), which is a goto basically, and highly non-functional in nature.</li>\n</ol>\n\n<p>Lambda is functionally safer and easier to reason about - I always use it instead of proc.</p>\n'}, {'answer_id': 303428, 'author': 'webmat', 'author_id': 6349, 'author_profile': 'https://Stackoverflow.com/users/6349', 'pm_score': 4, 'selected': False, 'text': '<p>I can\'t say much about the subtle differences. However, I can point out that Ruby 1.9 now allows optional parameters for lambdas and blocks.</p>\n\n<p>Here\'s the new syntax for the stabby lambdas under 1.9:</p>\n\n<pre><code>stabby = -&gt;(msg=\'inside the stabby lambda\') { puts msg }\n</code></pre>\n\n<p>Ruby 1.8 didn\'t have that syntax. Neither did the conventional way of declaring blocks/lambdas support optional args:</p>\n\n<pre><code># under 1.8\nl = lambda { |msg = \'inside the stabby lambda\'|  puts msg }\nSyntaxError: compile error\n(irb):1: syntax error, unexpected \'=\', expecting tCOLON2 or \'[\' or \'.\'\nl = lambda { |msg = \'inside the stabby lambda\'|  puts msg }\n</code></pre>\n\n<p>Ruby 1.9, however, supports optional arguments even with the old syntax:</p>\n\n<pre><code>l = lambda { |msg = \'inside the regular lambda\'|  puts msg }\n#=&gt; #&lt;Proc:0x0e5dbc@(irb):1 (lambda)&gt;\nl.call\n#=&gt; inside the regular lambda\nl.call(\'jeez\')\n#=&gt; jeez\n</code></pre>\n\n<p>If you wanna build Ruby1.9 for Leopard or Linux, check out <a href="http://programblings.com/2008/11/18/installing-ruby-19preview1-on-os-x-leopard/" rel="noreferrer">this article</a> (shameless self promotion).</p>\n'}, {'answer_id': 352857, 'author': 'krusty.ar', 'author_id': 43981, 'author_profile': 'https://Stackoverflow.com/users/43981', 'pm_score': 4, 'selected': False, 'text': "<p>A good way to see it is that lambdas are executed in their own scope (as if it was a method call), while Procs may be viewed as executed inline with the calling method, at least that's a good way of deciding wich one to use in each case.</p>\n"}, {'answer_id': 1043390, 'author': 'Dave Rapin', 'author_id': 34210, 'author_profile': 'https://Stackoverflow.com/users/34210', 'pm_score': 3, 'selected': False, 'text': '<p>I didn\'t notice any comments on the third method in the queston, "proc" which is deprecated, but handled differently in 1.8 and 1.9.</p>\n\n<p>Here\'s a fairly verbose example that makes it easy to see the differences between the three similar calls:</p>\n\n<pre><code>def meth1\n  puts "method start"\n\n  pr = lambda { return }\n  pr.call\n\n  puts "method end"  \nend\n\ndef meth2\n  puts "method start"\n\n  pr = Proc.new { return }\n  pr.call\n\n  puts "method end"  \nend\n\ndef meth3\n  puts "method start"\n\n  pr = proc { return }\n  pr.call\n\n  puts "method end"  \nend\n\nputs "Using lambda"\nmeth1\nputs "--------"\nputs "using Proc.new"\nmeth2\nputs "--------"\nputs "using proc"\nmeth3\n</code></pre>\n'}, {'answer_id': 1515670, 'author': 'Peter Wagenet', 'author_id': 181916, 'author_profile': 'https://Stackoverflow.com/users/181916', 'pm_score': 7, 'selected': False, 'text': '<p>To provide further clarification:</p>\n\n<p>Joey says that the return behavior of <code>Proc.new</code> is surprising. However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave. lambas on the other hand behave more like methods.</p>\n\n<p>This actually explains why Procs are flexible when it comes to arity (number of arguments) whereas lambdas are not. Blocks don\'t require all their arguments to be provided but methods do (unless a default is provided). While providing lambda argument default is not an option in Ruby 1.8, it is now supported in Ruby 1.9 with the alternative lambda syntax (as noted by webmat):</p>\n\n<pre><code>concat = -&gt;(a, b=2){ "#{a}#{b}" }\nconcat.call(4,5) # =&gt; "45"\nconcat.call(1)   # =&gt; "12"\n</code></pre>\n\n<p>And Michiel de Mare (the OP) is incorrect about the Procs and lambda behaving the same with arity in Ruby 1.9. I have verified that they still maintain the behavior from 1.8 as specified above.</p>\n\n<p><code>break</code> statements don\'t actually make much sense in either Procs or lambdas. In Procs, the break would return you from Proc.new which has already been completed. And it doesn\'t make any sense to break from a lambda since it\'s essentially a method, and you would never break from the top level of a method.</p>\n\n<p><code>next</code>, <code>redo</code>, and <code>raise</code> behave the same in both Procs and lambdas. Whereas <code>retry</code> is not allowed in either and will raise an exception.</p>\n\n<p>And finally, the <code>proc</code> method should never be used as it is inconsistent and has unexpected behavior. In Ruby 1.8 it actually returns a lambda! In Ruby 1.9 this has been fixed and it returns a Proc. If you want to create a Proc, stick with <code>Proc.new</code>.</p>\n\n<p>For more information, I highly recommend O\'Reilly\'s <em>The Ruby Programming Language</em> which is my source for most of this information.</p>\n'}, {'answer_id': 7678836, 'author': 'Evan Moran', 'author_id': 47593, 'author_profile': 'https://Stackoverflow.com/users/47593', 'pm_score': 4, 'selected': False, 'text': '<p>Short answer: What matters is what <code>return</code> does: lambda returns out of itself, and proc returns out of itself AND the function that called it. </p>\n\n<p>What is less clear is why you want to use each. lambda is what we expect things should do in a functional programming sense. It is basically an anonymous method with the current scope automatically bound. Of the two, lambda is the one you should probably be using.</p>\n\n<p>Proc, on the other hand, is really useful for implementing the language itself. For example you can implement "if" statements or "for" loops with them. Any return found in the proc will return out of the method that called it, not the just the "if" statement. This is how languages work, how "if" statements work, so my guess is Ruby uses this under the covers and they just exposed it because it seemed powerful.</p>\n\n<p>You would only really need this if you are creating new language constructs like loops, if-else constructs, etc.</p>\n'}, {'answer_id': 26635646, 'author': 'weakish', 'author_id': 222893, 'author_profile': 'https://Stackoverflow.com/users/222893', 'pm_score': 3, 'selected': False, 'text': '<p>lambda works as expected, like in other languages.</p>\n\n<p>The wired <code>Proc.new</code> is surprising and confusing.</p>\n\n<p>The <code>return</code> statement in proc created by <code>Proc.new</code> will not only return control just from itself, but <em>also from the method enclosing it</em>.</p>\n\n<pre><code>def some_method\n  myproc = Proc.new {return "End."}\n  myproc.call\n\n  # Any code below will not get executed!\n  # ...\nend\n</code></pre>\n\n<p>You can argue that <code>Proc.new</code> inserts code into the enclosing method, just like block.\nBut <code>Proc.new</code> creates an object, while block are <em>part of</em> an object.</p>\n\n<p>And there is another difference between lambda and <code>Proc.new</code>, which is their handling of (wrong) arguments.\nlambda complains about it, while <code>Proc.new</code> ignores extra arguments or considers the absence of arguments as nil.</p>\n\n<pre><code>irb(main):021:0&gt; l = -&gt; (x) { x.to_s }\n=&gt; #&lt;Proc:0x8b63750@(irb):21 (lambda)&gt;\nirb(main):022:0&gt; p = Proc.new { |x| x.to_s}\n=&gt; #&lt;Proc:0x8b59494@(irb):22&gt;\nirb(main):025:0&gt; l.call\nArgumentError: wrong number of arguments (0 for 1)\n        from (irb):21:in `block in irb_binding\'\n        from (irb):25:in `call\'\n        from (irb):25\n        from /usr/bin/irb:11:in `&lt;main&gt;\'\nirb(main):026:0&gt; p.call\n=&gt; ""\nirb(main):049:0&gt; l.call 1, 2\nArgumentError: wrong number of arguments (2 for 1)\n        from (irb):47:in `block in irb_binding\'\n        from (irb):49:in `call\'\n        from (irb):49\n        from /usr/bin/irb:11:in `&lt;main&gt;\'\nirb(main):050:0&gt; p.call 1, 2\n=&gt; "1"\n</code></pre>\n\n<p>BTW, <code>proc</code> in Ruby 1.8 creates a lambda, while in Ruby 1.9+ behaves like <code>Proc.new</code>, which is really confusing.</p>\n'}, {'answer_id': 29920634, 'author': 'Aleksei Matiushkin', 'author_id': 2035262, 'author_profile': 'https://Stackoverflow.com/users/2035262', 'pm_score': 2, 'selected': False, 'text': '<p>I am a bit late on this, but there is one great but little known thing about <code>Proc.new</code> not mentioned in comments at all. As by <a href="http://ruby-doc.org/core-2.2.1/Proc.html#method-c-new" rel="nofollow">documentation</a>:</p>\n\n<blockquote>\n  <p><code>Proc::new</code> may be called without a block only within a method with an attached block, in which case that <strong>block is converted to the <code>Proc</code></strong> object.</p>\n</blockquote>\n\n<p>That said, <code>Proc.new</code> lets to chain yielding methods:</p>\n\n<pre><code>def m1\n  yield \'Finally!\' if block_given?\nend\n\ndef m2\n  m1 &amp;Proc.new\nend\n\nm2 { |e| puts e } \n#⇒ Finally!\n</code></pre>\n'}, {'answer_id': 53316814, 'author': 'ComDubh', 'author_id': 1445986, 'author_profile': 'https://Stackoverflow.com/users/1445986', 'pm_score': 2, 'selected': False, 'text': "<p>It's worth emphasizing that <code>return</code> in a proc returns from the lexically enclosing method, i.e. <em>the method where the proc was created</em>, <strong>not</strong> the method that called the proc. This is a consequence of the closure property of procs. So the following code outputs nothing:</p>\n\n<pre><code>def foo\n  proc = Proc.new{return}\n  foobar(proc)\n  puts 'foo'\nend\n\ndef foobar(proc)\n  proc.call\n  puts 'foobar'\nend\n\nfoo\n</code></pre>\n\n<p>Although the proc executes in <code>foobar</code>, it was created in <code>foo</code> and so the <code>return</code> exits <code>foo</code>, not just <code>foobar</code>. As Charles Caldwell wrote above, it has a GOTO feel to it. In my opinion, <code>return</code> is fine in a block that is executed in its lexical context, but is much less intuitive when used in a proc that is executed in a different context.</p>\n"}]
['https://Stackoverflow.com/questions/626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136/']