Proc.new / proc / lambda / ->
| Since: | Ruby 1.9(2007) |
|---|
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
sample_proc_lambda.rb
# Creates and calls a Proc.
greet = Proc.new { |name| puts "Hello, #{name}!" }
greet.call("Yagami Iori") # Hello, Yagami Iori!
greet.("Terry Bogard") # Hello, Terry Bogard!
# 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) }
Running the code produces the following output:
ruby proc_lambda.rb Hello, Yagami Iori! Hello, Terry Bogard! 16 25 7 3 HELLO olleh hell0
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. The strategy pattern is a design pattern that makes an algorithm interchangeable at runtime. 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.