0
0
Rubyprogramming~5 mins

Proc vs lambda differences (arity, return) in Ruby

Choose your learning style9 modes available
Introduction

Procs and lambdas are ways to store blocks of code to run later. They look similar but behave differently in how they handle arguments and returns.

When you want to reuse a piece of code with flexible or strict argument rules.
When you want to control how returning from the code block affects the surrounding method.
When you need to pass a block of code as an object to methods or variables.
Syntax
Ruby
my_proc = Proc.new { |x| puts x }
my_lambda = ->(x) { puts x }

Procs are created with Proc.new or proc.

Lambdas are created with lambda or the arrow syntax ->.

Examples
Proc ignores missing arguments and sets them to nil.
Ruby
my_proc = Proc.new { |x, y| puts "x: #{x}, y: #{y}" }
my_proc.call(1)
Lambda checks the number of arguments strictly and raises an error if they don't match.
Ruby
my_lambda = ->(x, y) { puts "x: #{x}, y: #{y}" }
my_lambda.call(1)
Proc's return exits the whole method immediately.
Ruby
def test_proc
  my_proc = Proc.new { return "From proc" }
  my_proc.call
  return "From method"
end
puts test_proc
Lambda's return exits only the lambda, not the method.
Ruby
def test_lambda
  my_lambda = -> { return "From lambda" }
  result = my_lambda.call
  return "From method after lambda"
end
puts test_lambda
Sample Program

This program shows how return works differently in proc and lambda. The proc's return exits the method immediately, so the lambda call is never reached.

Ruby
def proc_vs_lambda
  my_proc = Proc.new { |x| return "Proc returned: #{x}" }
  my_lambda = ->(x) { return "Lambda returned: #{x}" }

  proc_result = my_proc.call(10)
  lambda_result = my_lambda.call(20)

  "proc_result: #{proc_result}, lambda_result: #{lambda_result}"
end

puts proc_vs_lambda
OutputSuccess
Important Notes

Procs are lenient with arguments; missing ones become nil.

Lambdas enforce the exact number of arguments.

Return inside a proc exits the surrounding method, but return inside a lambda exits only the lambda.

Summary

Procs are flexible with arguments and their return exits the whole method.

Lambdas check arguments strictly and their return exits only the lambda.

Choose based on how you want argument checking and return behavior.