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. <!--more--> {% codeblock lang:ruby%} myproc = proc do |a| puts "number is #{a}" end myproc.call(10 ) # number is 10 {% endcodeblock %} lambda {% codeblock lang:ruby%} mylambda = lambda do|a| puts "number is #{a}" end mylambda.call(10 ) # number is 10 {% endcodeblock %} Difference between both of themin Ruby-1.9.3
-
lambda is very specific for parameters passing to it but proc not -:
{% codeblock lang:ruby%}
myproc = proc do|a|
puts "this is proc"
end
myproc.call #this is proc
{% endcodeblock %}
{% codeblock lang:ruby%}
mylambda =lambda do |a|
puts "this is lambda"
end
mylambda.call #will throw error "wrong number of arguments"
{% endcodeblock %}
In ruby-1.8.7 it just give you warning not error -
Second is about return mean -:
{% codeblock lang:ruby%}
def runaproc(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 {% endcodeblock %} the output is -: {% codeblock lang:ruby%} starting proc this is lambda Ending proc starting proc this is proc {% endcodeblock %}
so difference is lambda return within it but the proc return from where it is called if we modified test_proc method like
{% codeblock lang:ruby%} def testproc runaproc proc{puts 'this is proc'; return} runa_proc lambda{puts 'this is lambda'; return} end {% endcodeblock %} now the output will be -:
{% codeblock lang:ruby%} starting proc this is proc {% endcodeblock %}