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
my_proc = proc do |a|
  puts "number is #{a}"
end
my_proc.call(10 ) # number is 10

lambda

1
2
3
4
my_lambda = lambda do|a|
  puts "number is #{a}"
end
my_lambda.call(10 ) # number is 10

Difference between both of themin Ruby-1.9.3

  1. 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"
    
    
    In ruby-1.8.7 it just give you warning not error
  2. 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
    
    
    the output is -:
    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
def test_proc
  run_a_proc proc{puts 'this is proc'; return}
  run_a_proc lambda{puts 'this is lambda'; return}
end

now the output will be –:

1
2
starting proc
this is proc