What's the difference between a lambda, a block and a proc?
- The difference between Blocks and Procs
- Procs is an Object, but Block is not an object, it is just a code snippet
- Each method can only pass one code segment at most, but can pass multiple Proc
- Similarities and differences between Proc and Lambda
proc = Proc.new {puts "hello world"}
lambda = lambda {puts "hello world"}
proc.class # rerturn 'Proc'
lambda.class # return 'Proc'
|
As can be seen from the above, in fact, Proc and lambda are both Proc objects.
lambdaWill check the number of parameters but procnot
lam = lambda { |x| puts x}
lam.call(2) # print 2
lam.call # Argument Error: wrong number of arguments (0 for 1)
lam.call(1,2) # Argument Error: wrong number of arguments (2 for 1)
pro = Proc.new {|x| puts x}
proc.call(2) # print 2
proc.call # return nil
proc.call(1,2) # print 1
|
lambda And proc the meaning of the 'return' key is not the same, but proc the return only call in the method body
def lambda_test
lam = lambda { return }
lam.call
puts "hello"
end
lambda_test # puts 'hello'
def proc_test
pro = Proc.new {return}
proc.call
puts 'hello'
end
proc_test # return nil hello
|
Refer: What Is the Difference Between a Block, a Proc, and a Lambda in Ruby?