In Ruby, a Proc (short for procedure) is an object that encapsulates a block of code. It's a powerful feature that allows you to store and pass around chunks of code as if they were variables.
A Proc is essentially a named block. It's similar to a method, but it's not bound to an object. Procs are incredibly versatile and can be used in various scenarios where you need to pass behavior as an argument.
There are several ways to create a Proc in Ruby:
# Using Proc.new
greeting = Proc.new { |name| puts "Hello, #{name}!" }
# Using the proc method
square = proc { |x| x * x }
# Using the lambda shorthand (creates a special kind of Proc)
multiply = ->(a, b) { a * b }
Once you've created a Proc, you can call it using the call
method or the shorthand .[]
syntax:
greeting.call("Ruby") # Outputs: Hello, Ruby!
square[5] # Returns: 25
multiply[3, 4] # Returns: 12
While Procs and blocks are similar, Procs offer more flexibility. Unlike blocks, Procs can be stored in variables, passed as arguments, and reused multiple times.
Methods can accept Procs as arguments, allowing for powerful customization:
def apply_twice(proc, value)
proc.call(proc.call(value))
end
double = proc { |x| x * 2 }
puts apply_twice(double, 3) # Outputs: 12
While Procs and lambdas are both instances of the Proc class, they have subtle differences in argument handling and return behavior. Lambdas check the number of arguments strictly, while Procs are more lenient.
Procs are a fundamental part of Ruby's functional programming capabilities. They provide a way to encapsulate behavior, making your code more modular and flexible. By mastering Procs, you'll be able to write more elegant and reusable Ruby code.
For more advanced usage of Procs, explore topics like closures and metaprogramming in Ruby.