Method Objects
In this page:
Method Objects
method(:name) converts an existing method into a callable Method object, which behaves much like a lambda and can be stored, passed around, or converted with .to_proc. This lets you treat a named method as a first-class value, the same way you would a lambda. It's especially handy for passing an existing method directly to something like map without wrapping it in a block.
Note: numbers.map(&method(:square)) passes an existing method directly into map, avoiding a redundant wrapper block.
Example: Method Objects
def square(x)
x * x
end
square_method = method(:square)
puts square_method.call(5)
numbers = [1, 2, 3, 4]
puts numbers.map(&method(:square)).inspect
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: