From: Robert Klemme Date: 2007-02-04T20:20:06+09:00 Subject: Re: Proc vs lambda vs proc On 04.02.2007 04:55, Minkoo Seo wrote: > I got a question on Proc.new and lambda { ... }. AFAIK, there's two > differences between Proc.new(=proc) and lambda. I think you have it slightly wrong: "proc" and "lambda" are aliases while "Proc.new" works different. > The first one is that > Proc.new does not check the number of arguments passed to it while > lambda does. Correct: irb(main):001:0> f1 = Proc.new {|a,b|a+b} => # irb(main):002:0> f2 = proc {|a,b|a+b} => # irb(main):003:0> f3 = lambda {|a,b|a+b} => # irb(main):004:0> f1[1,2] => 3 irb(main):005:0> f1[1,2,3] => 3 irb(main):006:0> f2[1,2,3] ArgumentError: wrong number of arguments (3 for 2) from (irb):2 from (irb):6:in `[]' from (irb):6 from :0 irb(main):007:0> f3[1,2,3] ArgumentError: wrong number of arguments (3 for 2) from (irb):3 from (irb):7:in `[]' from (irb):7 from :0 irb(main):008:0> f2[1,2] => 3 irb(main):009:0> f3[1,2] => 3 > The secondis that lambda returns as we expect, i.e., it > returns value, while Proc.new does not. I do not understand what you mean here. All three return what you expect (apart from an exception in the case of wrong # of arguments. > Though Proc.new lacks several advantages that lambda has, Which advantages do you refer to? > I guess > there might be some situation where Proc.new is more suitable than > lambda. As an example, some code blocks that have to executed > thousands times might run more faster than lambda because it does not > have to check the # of arguments, thereby decreasing computational > overhead. I suggest to benchmark a concrete example if you are interested in timings. My guess is that the parameter checking overhead is negligible. > What is your opinion? I usually use lambda because it most resembles the term "lambda expression". But I guess this is just a matter of taste / personal preference. Kind regards robert