0
0
Rubyprogramming~30 mins

Proc vs lambda differences (arity, return) in Ruby - Hands-On Comparison

Choose your learning style9 modes available
Proc vs Lambda Differences (Arity, Return) in Ruby
📖 Scenario: Imagine you are learning how to use two similar tools in Ruby called Proc and lambda. Both can hold blocks of code to run later, but they behave differently when it comes to how many inputs they accept (arity) and how they handle the return statement.
🎯 Goal: You will create a Proc and a lambda that each take exactly one number, then try to return from inside them. You will see how they behave differently with input counts and return.
📋 What You'll Learn
Create a Proc named my_proc that takes one argument and returns double the value.
Create a lambda named my_lambda that takes one argument and returns double the value.
Call my_proc with two arguments and observe behavior.
Call my_lambda with two arguments and observe behavior.
Show how return works inside Proc and lambda.
💡 Why This Matters
🌍 Real World
Understanding Procs and lambdas helps you write flexible and clear Ruby code, especially when passing blocks or callbacks.
💼 Career
Many Ruby jobs require knowledge of blocks, Procs, and lambdas to write clean, maintainable code and handle functional programming patterns.
Progress0 / 5 steps
1
Create a Proc named my_proc that takes one argument and returns double the value
Create a Proc called my_proc that takes one argument x and returns x * 2.
Ruby
Need a hint?

Use Proc.new { |x| x * 2 } to create the Proc.

2
Create a lambda named my_lambda that takes one argument and returns double the value
Create a lambda called my_lambda that takes one argument x and returns x * 2.
Ruby
Need a hint?

Use my_lambda = ->(x) { x * 2 } to create the lambda.

3
Call my_proc with two arguments and observe behavior
Call my_proc with arguments 5 and 10 using my_proc.call(5, 10) and assign the result to proc_result.
Ruby
Need a hint?

Use proc_result = my_proc.call(5, 10) to call the Proc with two arguments.

4
Call my_lambda with two arguments and observe behavior
Call my_lambda with arguments 5 and 10 using my_lambda.call(5, 10) inside a begin-rescue block to catch errors. Assign the error message to lambda_error if an error occurs.
Ruby
Need a hint?

Use a begin-rescue block to catch the ArgumentError when calling the lambda with wrong number of arguments.

5
Show how return works inside Proc and lambda
Create a method test_return that calls a Proc with a return inside and then prints 'After proc'. Then create a method test_lambda_return that calls a lambda with a return inside and then prints 'After lambda'. Call both methods and assign their outputs to proc_output and lambda_output respectively.
Ruby
Need a hint?

Remember that return inside a Proc exits the whole method, but inside a lambda it only exits the lambda.