Monday, January 9, 2012

Proc vs lamda in ruby

The are two major difference between procs and lambda 

1.) A proc can break the parent method, return values from it, and raise exceptions, while such statements in lambda will only affect the lambda object. 


def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo"
end

def bar
  f = lambda { return "return from lambda" }
  f.call # control does not leave bar here
  return "return from bar"
end

puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"

2.) The other difference is unlike Procs, lambdas check the number of arguments passed.

def some_method(code)
  one, two = 1, 2
  code.call(one, two)
end

some_method(Proc.new{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

some_method(lambda{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

# => First argument: 1 and  and Second argument 2 and Third argument NilClass
# *.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError)

We see with the Proc example, extra variables are set to nil. However with lambdas, Ruby throws an error instead.

No comments:

Post a Comment