What Proc and Lambda have in common:
- Similar syntax
proc.new{|n| N**2}
lambda{|n| N**2}
- Can be called with the. Call method
Hello_proc = proc.new{puts "hello!"}
Hello_proc.call #Hello!
Hello_lambda = lambda{puts "hello!"}
Hello_lambda.call #Hello!
- can be converted to block with & keyword
Nums = [1,3,4,5,6]
Cube_proc = proc.new{|n| n**3}
Cube_nums_proc = Nums.map (&cube_proc) #[1,27,64 ...]
Cube_lambda = lambda{|n| n**3}
Cube_nums_lambda = Nums.map (&CUBE_LAMBDA) #[1,27,64 ...]
- Both are object
The difference between Proc and lambda:
- Lambda checks the parameters passed in, and if an incorrect argument is passed, throw an error; Proc does not check, even if an incorrect parameter is passed, it is ignored, and nil is assigned to the result (assign to any of that is
nil
missing.).
- When the lambda returns, the control is returned to its calling function, and proc is not exchanged.
def Batman_ironman_proc
Victor = proc.new {return "Batman'll win!"}
Victor.call
"Iron man would win!"
End
Puts Batman_ironman_proc
def BATMAN_IRONMAN_LAMBDA
Victor = lambda {return "Batman'll win!"}
Victor.call
"Iron man would win!"
End
Puts Batman_ironman_lambda
Output = = = = = "Batman'll win!
Iron man would win!
The similarities and differences between Ruby Proc and Lambda