Middle
What is a lambda and a procedure in Ruby?
sobes.tech AI
Answer from AI
A lambda and a procedure in Ruby are Proc objects that encapsulate blocks of code.
The main differences lie in their behavior when returning values and the number of arguments they accept:
-
Lambda:
- Strictly enforces the number of arguments (like a regular method).
returninside a lambda returns a value only from itself.
# Example of a lambda lambda_proc = lambda { |a, b| return a + b } puts lambda_proc.call(1, 2) # 3 # Error: incorrect number of arguments # lambda_proc.call(1) -
Proc:
- Less strict about the number of arguments (may not raise an error if more or fewer arguments are provided).
returninside a Proc returns a value from the context where the Proc was defined (likereturnin a block).
# Example of a Proc proc_proc = Proc.new { |a, b| return a + b } def method_with_proc proc_proc = Proc.new { return "return from method" } proc_proc.call "this text will not be shown" end puts method_with_proc # return from method # Does not raise an error with incorrect number of arguments (behavior may be unpredictable) # proc_proc.call(1)
Comparison:
| Characteristic | Lambda | Proc |
|---|---|---|
| Argument control | Strict | Non-strict |
return behavior |
Returns from the lambda itself | Returns from the context |
| Class | Proc (but with lambda? flag) |
Proc |
| Creation | lambda { ... }, -> { ... } |
Proc.new { ... }, proc { ... } |
In most cases, for passing blocks of behavior similar to methods, it is preferable to use lambdas due to their more predictable behavior with arguments and return. Procs are more often used for lower-level tasks or where their specific return behavior is desired.