Basic Difference Between Proc and Lambda in Ruby
Proc => Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.
1 2 3 4 |
|
lambda
1 2 3 4 |
|
Difference between both of themin Ruby-1.9.3
-
lambda is very specific for parameters passing to it but proc not -:
1 2 3 4 5
my_proc = proc do|a| puts "this is proc" end my_proc.call #this is proc
1 2 3 4 5
my_lambda =lambda do |a| puts "this is lambda" end my_lambda.call #will throw error "wrong number of arguments"
-
Second is about return mean -:
1 2 3 4 5 6 7 8 9 10 11 12
def run_a_proc(p) puts "starting proc" p.call puts "Ending proc" end def test_proc run_a_proc lambda{puts 'this is lambda'; return} run_a_proc proc{puts 'this is proc'; return} end test_proc
1 2 3 4 5 6
starting proc this is lambda Ending proc starting proc this is proc
so difference is lambda return within it but the proc return from where it is called if we modified test_proc method like
1 2 3 4 |
|
now the output will be –:
1 2 |
|