Proc.new / proc / lambda / ->
Proc and Lambda are objects that wrap blocks. You can assign them to variables and call them multiple times.
Syntax
# Creates a Proc object.
procedure = Proc.new { |arg| process }
procedure = proc { |arg| process }
# Creates a Lambda.
func = lambda { |arg| process }
func = ->(arg) { process } # Arrow syntax (Ruby 1.9 and later)
# Calls a Proc / Lambda.
procedure.call(arg)
procedure.(arg) # Shorthand for .call
procedure[arg] # You can also call with []
Differences Between Proc and Lambda
| Feature | Proc | Lambda |
|---|---|---|
| Argument count check | Not checked (extra arguments are ignored). | Strictly checked. |
| Behavior of return | Returns from the enclosing method as well. | Returns only from inside the Lambda. |
| lambda? | false | true |
Sample Code
# Creates and calls a Proc.
greet = Proc.new { |name| puts "Hello, #{name}!" }
greet.call("Tanaka") # Hello, Tanaka!
greet.("Yamada") # Hello, Yamada!
# Creates a Lambda using the arrow syntax.
square = ->(n) { n ** 2 }
puts square.call(4) # 16
puts square.(5) # 25
# Lambda strictly checks the number of arguments.
# The following raises an error.
# square.call(4, 5) # ArgumentError: wrong number of arguments
# Proc fills in missing arguments with nil.
add = Proc.new { |a, b| puts (a.to_i + b.to_i) }
add.call(3, 4) # 7
add.call(3) # 3 (b is nil, treated as 0)
# Stores Lambdas in an array and applies them in sequence.
transforms = [
->(s) { s.upcase },
->(s) { s.reverse },
->(s) { s.gsub("o", "0") }
]
text = "hello"
transforms.each { |fn| puts fn.call(text) }
Overview
Both Proc and Lambda wrap blocks as objects, but they differ in argument checking and the behavior of return. In general, Lambda is recommended for its safer behavior. The arrow syntax ->() is concise and commonly used in modern Ruby code.
Storing a Proc or Lambda in a variable enables patterns such as callbacks, the strategy pattern, and lazy evaluation. Using return inside a Proc exits the enclosing method as well, so avoid using return in a Proc, or rely on the value of the last expression as the return value.
If you find any errors or copyright issues, please contact us.