tags:

views:

2910

answers:

10

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?

Edit

@Mike Stone: there's no difference between 1.8 and 1.9 in this regard.

@Accordeon Guy: that's the difference I had in mind, but I don't think it's the whole story. What about next/break/return in procs? What about Ruby 1.9? What about scopes, and returning procs from a method?

+14  A: 

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

Mike Stone
+48  A: 

Another important but subtle difference is in the way procs created with lambda and procs created with Proc.new 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 behaviour (as well as less typing), I tend to favour using lambda over Proc.new when making procs.

Joey deVilla
A: 

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
+2  A: 

A good overview for how blocks, lamda and proc work in Ruby, with Ruby :-) - Closures in Ruby.

+2  A: 

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
+3  A: 

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.

+2  A: 

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
+1  A: 

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
+1  A: 

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
where did you read that `proc` was deprecated?
banister
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
@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
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
+3  A: 

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