Proc vs lambda differences (arity, return) in Ruby - Performance Comparison
We want to understand how the behavior of Procs and lambdas affects the flow of a Ruby program.
Specifically, how their differences in handling arguments and return statements impact execution steps.
Analyze the time complexity of the following Ruby code using Proc and lambda.
my_proc = Proc.new { |x, y| x + y }
my_lambda = ->(x, y) { x + y }
result_proc = my_proc.call(1) # Missing one argument
result_lambda = my_lambda.call(1) # Missing one argument (raises ArgumentError)
my_proc = Proc.new { return 10 }
my_lambda = -> { return 20 }
result_proc_return = my_proc.call
result_lambda_return = my_lambda.call
This code shows how Procs and lambdas handle argument counts and return statements differently.
Look for operations that repeat or cause the program to jump in execution.
- Primary operation: Calling Proc and lambda objects.
- How many times: Each call happens once, but the behavior inside affects how the program continues.
When calling Procs or lambdas, the number of arguments affects whether the call succeeds or raises an error.
| Input Size (arguments) | Approx. Operations |
|---|---|
| 1 (missing argument) | Proc ignores missing, lambda raises error |
| 2 (correct arguments) | Both execute normally |
| 3 (extra argument) | Proc ignores extra, lambda raises error |
Pattern observation: Procs are flexible with argument count, lambdas strictly check it, which can cause errors and stop execution.
Time Complexity: O(1)
This means calling a Proc or lambda takes a constant amount of time regardless of input size, but behavior differences affect program flow.
[X] Wrong: "Procs and lambdas behave the same when called with wrong number of arguments."
[OK] Correct: Procs ignore missing or extra arguments, while lambdas raise errors, which can stop the program unexpectedly.
Understanding these differences helps you write clearer Ruby code and avoid bugs related to argument handling and returns.
What if we replaced the lambda with a method? How would the time complexity and behavior change when called with wrong arguments?