345

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

  • What are those differences?
  • Can you give guidelines on how to decide which one to choose?
  • In Ruby 1.9, proc and lambda are different. What's the deal?
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Michiel de Mare
  • 41,982
  • 29
  • 103
  • 134
  • 3
    See also: the Ruby Programming Language book by Matz and Flanagan, it has comprehensively covered this topic. proc behaves like a block - yield semantics, where as lambda behaves like a method - method call semantics. Also return, break, et. all behave diff in procs n lambdas – Gishu Feb 08 '10 at 13:03
  • 1
    Also see a detailed post on [Control flow differences between Ruby Procs and Lambdas](http://www.akshay.cc/blog/2010-02-14-control-flow-differences-between-ruby-procs-and-lambdas.html) – Akshay Rawat Mar 31 '13 at 13:13
  • you have accepted the answer that only says whats the difference between proc and lambda, while the title of your question is when to use those things – Shri Sep 16 '16 at 05:58

14 Answers14

383

Another important but subtle difference between procs created with lambda and procs created with Proc.new is how they handle the return statement:

  • In a lambda-created proc, the return statement returns only from the proc itself
  • In a Proc.new-created proc, the return statement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!

Here's lambda-created proc's return in action. It behaves in a way that you probably expect:

def whowouldwin

  mylambda = lambda {return "Freddy"}
  mylambda.call

  # mylambda gets called and returns "Freddy", and execution
  # continues on the next line

  return "Jason"

end


whowouldwin
#=> "Jason"

Now here's a Proc.new-created proc's return doing the same thing. You're about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:

def whowouldwin2

  myproc = Proc.new {return "Freddy"}
  myproc.call

  # myproc gets called and returns "Freddy", 
  # but also returns control from whowhouldwin2!
  # The line below *never* gets executed.

  return "Jason"

end


whowouldwin2         
#=> "Freddy"

Thanks to this surprising behavior (as well as less typing), I tend to favor using lambda over Proc.new when making procs.

mbigras
  • 7,664
  • 11
  • 50
  • 111
Joey deVilla
  • 8,403
  • 2
  • 29
  • 15
  • 12
    Then there is also the `proc` method. Is it just a shorthand for `Proc.new`? – panzi Nov 19 '10 at 15:49
  • 6
    @panzi, yes, [`proc` is equivalent to `Proc.new`](http://www.ruby-doc.org/core/classes/Kernel.html#M001446) – ma11hew28 Feb 17 '11 at 19:13
  • 4
    @mattdipasquale In my tests, `proc` acts like `lambda` and not like `Proc.new` with regard to return statements. That means the ruby doc is inaccurate. – Kelvin Aug 02 '11 at 15:10
  • 32
    @mattdipasquale Sorry I was only half right. `proc` acts like `lambda` in 1.8, but acts like `Proc.new` in 1.9. See Peter Wagenet's answer. – Kelvin Aug 02 '11 at 15:20
  • 60
    Why is this "surprising" behavior? A `lambda` is an anonymous method. Since it's a method, it returns a value, and the method that called it can do with it whatever it wants, including ignoring it and returning a different value. A `Proc` is like pasting in a code snippet. It doesn't act like a method. So when a return happens within the `Proc`, that's just part of the code of the method that called it. – Arcolye Dec 24 '12 at 03:13
  • 3
    As pointed out by Arcolye, "Procs in Ruby are drop in code snippets, not methods". From http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/. So it's like the return is in whowouldwin2 itself. – Pietro Jan 12 '13 at 16:35
  • 4
    I believe a major difference is also that `Proc`s don't throw errors when you provide missing/extra arguments, while `lambda`s will throw a `wrong number of arguments` error – bigpotato Aug 01 '13 at 18:24
  • 2
    The answer is unclear on this point and Arcoyle's comment above is simply wrong: a `return` in a Proc returns from the context that created the proc, **not the context that called the proc**. This error is everywhere! – ComDubh Dec 14 '18 at 16:19
95

To provide further clarification:

Joey says that the return behavior of Proc.new 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.

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):

concat = ->(a, b=2){ "#{a}#{b}" }
concat.call(4,5) # => "45"
concat.call(1)   # => "12"

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.

break 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.

next, redo, and raise behave the same in both Procs and lambdas. Whereas retry is not allowed in either and will raise an exception.

And finally, the proc 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 Proc.new.

For more information, I highly recommend O'Reilly's The Ruby Programming Language which is my source for most of this information.

Peter Wagenet
  • 4,976
  • 22
  • 26
  • 1
    """However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave.""" <- block is part of an object, while Proc.new creates an object. Both lambda and Proc.new creates an object whose class is Proc, why diff? – weakish Oct 29 '14 at 16:13
  • 2
    As of Ruby 2.5, `break` from Procs raises `LocalJumpError`, whereas `break` from lambdas behaves just like `return` (*i.e.*, `return nil`). – Masa Sakano Oct 16 '18 at 20:35
42

I found this page which shows what the difference between Proc.new and lambda are. According to the page, the only difference is that a lambda is strict about the number of arguments it accepts, whereas Proc.new converts missing arguments to nil. Here is an example IRB session illustrating the difference:

irb(main):001:0> l = lambda { |x, y| x + y }
=> #<Proc:0x00007fc605ec0748@(irb):1>
irb(main):002:0> p = Proc.new { |x, y| x + y }
=> #<Proc:0x00007fc605ea8698@(irb):2>
irb(main):003:0> l.call "hello", "world"
=> "helloworld"
irb(main):004:0> p.call "hello", "world"
=> "helloworld"
irb(main):005:0> l.call "hello"
ArgumentError: wrong number of arguments (1 for 2)
    from (irb):1
    from (irb):5:in `call'
    from (irb):5
    from :0
irb(main):006:0> p.call "hello"
TypeError: can't convert nil into String
    from (irb):2:in `+'
    from (irb):2
    from (irb):6:in `call'
    from (irb):6
    from :0

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.

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).

Flip
  • 6,233
  • 7
  • 46
  • 75
Mike Stone
  • 44,224
  • 30
  • 113
  • 140
  • 2
    procs also return differently than lambdas. – Cam Feb 20 '13 at 20:10
  • """Proc.new converts missing arguments to nil""" Proc.new also ignores extra arguments (of course lambda complains this with an error). – weakish Oct 29 '14 at 16:14
15

Proc is older, but the semantics of return are highly counterintuitive to me (at least when I was learning the language) because:

  1. If you are using proc, you are most likely using some kind of functional paradigm.
  2. Proc can return out of the enclosing scope (see previous responses), which is a goto basically, and highly non-functional in nature.

Lambda is functionally safer and easier to reason about - I always use it instead of proc.

Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47
11

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.

Here's the new syntax for the stabby lambdas under 1.9:

stabby = ->(msg='inside the stabby lambda') { puts msg }

Ruby 1.8 didn't have that syntax. Neither did the conventional way of declaring blocks/lambdas support optional args:

# under 1.8
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }
SyntaxError: compile error
(irb):1: syntax error, unexpected '=', expecting tCOLON2 or '[' or '.'
l = lambda { |msg = 'inside the stabby lambda'|  puts msg }

Ruby 1.9, however, supports optional arguments even with the old syntax:

l = lambda { |msg = 'inside the regular lambda'|  puts msg }
#=> #<Proc:0x0e5dbc@(irb):1 (lambda)>
l.call
#=> inside the regular lambda
l.call('jeez')
#=> jeez

If you wanna build Ruby1.9 for Leopard or Linux, check out this article (shameless self promotion).

webmat
  • 58,466
  • 12
  • 54
  • 59
  • Optional params within lambda's were much needed, I'm glad they've added it in 1.9. I assume blocks can also have optional parameters then too(in 1.9)? – mpd Dec 08 '10 at 17:43
  • you're not demonstrating default parameters in blocks, only lambdas – iconoclast Mar 24 '13 at 22:43
11

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.

krusty.ar
  • 4,015
  • 1
  • 25
  • 28
11

Short answer: What matters is what return does: lambda returns out of itself, and proc returns out of itself AND the function that called it.

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.

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.

You would only really need this if you are creating new language constructs like loops, if-else constructs, etc.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Evan Moran
  • 3,825
  • 34
  • 20
  • 3
    "lambda returns out of itself, and proc returns out of itself AND the function that called it" is plain wrong and a very common misunderstanding. A proc is a closure and returns from the method that created it. See my full answer elsewhere on the page. – ComDubh Nov 15 '18 at 10:11
7

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.

Here's a fairly verbose example that makes it easy to see the differences between the three similar calls:

def meth1
  puts "method start"

  pr = lambda { return }
  pr.call

  puts "method end"  
end

def meth2
  puts "method start"

  pr = Proc.new { return }
  pr.call

  puts "method end"  
end

def meth3
  puts "method start"

  pr = proc { return }
  pr.call

  puts "method end"  
end

puts "Using lambda"
meth1
puts "--------"
puts "using Proc.new"
meth2
puts "--------"
puts "using proc"
meth3
Dave Rapin
  • 1,471
  • 14
  • 18
  • 1
    Matz had stated that he planned to deprecate it because it was confusing to have proc and Proc.new returning different results. In 1.9 they behave the same though (proc is an alias to Proc.new). http://eigenclass.org/hiki/Changes+in+Ruby+1.9#l47 – Dave Rapin Jan 30 '10 at 13:18
  • @banister : `proc` returned a lambda in 1.8 ; it has now been fixed to return a proc in 1.9 - however this is a breaking change ; hence not recommended to use anymore – Gishu Feb 08 '10 at 13:05
  • I think the pickaxe says in a footnote somewhere that proc is effectively depricated or something. I don't have the exact page number. – dertoni Jun 04 '10 at 09:20
7

Closures in Ruby is a good overview for how blocks, lambda and proc work in Ruby, with Ruby.

swrobel
  • 4,053
  • 2
  • 33
  • 42
  • I stopped reading this after I read "a function can't accept multiple blocks -- violating the principle that closures can be passed around freely as values." Blocks are not closures. Procs are, and a function can accept multiple procs. – ComDubh Dec 14 '18 at 16:10
6

lambda works as expected, like in other languages.

The wired Proc.new is surprising and confusing.

The return statement in proc created by Proc.new will not only return control just from itself, but also from the method enclosing it.

def some_method
  myproc = Proc.new {return "End."}
  myproc.call

  # Any code below will not get executed!
  # ...
end

You can argue that Proc.new inserts code into the enclosing method, just like block. But Proc.new creates an object, while block are part of an object.

And there is another difference between lambda and Proc.new, which is their handling of (wrong) arguments. lambda complains about it, while Proc.new ignores extra arguments or considers the absence of arguments as nil.

irb(main):021:0> l = -> (x) { x.to_s }
=> #<Proc:0x8b63750@(irb):21 (lambda)>
irb(main):022:0> p = Proc.new { |x| x.to_s}
=> #<Proc:0x8b59494@(irb):22>
irb(main):025:0> l.call
ArgumentError: wrong number of arguments (0 for 1)
        from (irb):21:in `block in irb_binding'
        from (irb):25:in `call'
        from (irb):25
        from /usr/bin/irb:11:in `<main>'
irb(main):026:0> p.call
=> ""
irb(main):049:0> l.call 1, 2
ArgumentError: wrong number of arguments (2 for 1)
        from (irb):47:in `block in irb_binding'
        from (irb):49:in `call'
        from (irb):49
        from /usr/bin/irb:11:in `<main>'
irb(main):050:0> p.call 1, 2
=> "1"

BTW, proc in Ruby 1.8 creates a lambda, while in Ruby 1.9+ behaves like Proc.new, which is really confusing.

weakish
  • 28,682
  • 5
  • 48
  • 60
3

I am a bit late on this, but there is one great but little known thing about Proc.new not mentioned in comments at all. As by documentation:

Proc::new may be called without a block only within a method with an attached block, in which case that block is converted to the Proc object.

That said, Proc.new lets to chain yielding methods:

def m1
  yield 'Finally!' if block_given?
end

def m2
  m1 &Proc.new
end

m2 { |e| puts e } 
#⇒ Finally!
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Interesting, it does the same thing as declaring a `&block` argument in the `def`, but without having to do that in the def arg list. – jrochkind Feb 08 '16 at 05:02
3

To elaborate on Accordion Guy's response:

Notice that Proc.new creates a proc out by being passed a block. I believe that lambda {...} is parsed as a sort of literal, rather than a method call which passes a block. returning from inside a block attached to a method call will return from the method, not the block, and the Proc.new case is an example of this at play.

(This is 1.8. I don't know how this translates to 1.9.)

Peeja
  • 13,683
  • 11
  • 58
  • 77
3

It's worth emphasizing that return in a proc returns from the lexically enclosing method, i.e. the method where the proc was created, not the method that called the proc. This is a consequence of the closure property of procs. So the following code outputs nothing:

def foo
  proc = Proc.new{return}
  foobar(proc)
  puts 'foo'
end

def foobar(proc)
  proc.call
  puts 'foobar'
end

foo

Although the proc executes in foobar, it was created in foo and so the return exits foo, not just foobar. As Charles Caldwell wrote above, it has a GOTO feel to it. In my opinion, return 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.

ComDubh
  • 793
  • 4
  • 18
1

The difference in behaviour with return is IMHO the most important difference between the 2. I also prefer lambda because it's less typing than Proc.new :-)

Orion Edwards
  • 121,657
  • 64
  • 239
  • 328
  • 2
    To update: procs can now be created using `proc {}`. I'm not sure when this went into effect, but it's (slightly) easier than having to type Proc.new. – aceofbassgreg Aug 17 '13 at 15:42