Syntax
object.method(:name); callable.call(argument); items.map(&callable)Examples
Bound Method Objects
Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
class Calculator
def double(value)
value * 2
end
end
operation = Calculator.new.method(:double)
puts operation.call(4)
p [1, 2, 3].map(&operation)- Expected output: 8 [2, 4, 6]
- operation retains its Calculator receiver. The & conversion supplies the same bound operation as the map block.
Best practices
- Use method objects when passing an existing operation expresses intent better than wrapping it in a lambda.
- Avoid retaining bound methods longer than needed when their receivers hold large resources.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation