Method Objects
A method object turns an existing method into something you can carry around and call later, like saving a friend's number in your phone. You can then pass it to other code.
In this page:
Syntax
method_object = method(:method_name)
method_object.call(argument)
collection.map(&method(:method_name))
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
method(square)without the colon, which callssquareright away instead of getting the Method object; usemethod(:square). - Using
&method(:square)without the&, somapgets the Method as an argument, not a block. - Expecting the Method object to change when the method is redefined.
Chapter Summary
- Blocks and
yieldpass code to methods. - Procs and lambdas store code in objects, and they differ in how they handle arguments and returns.
- Method objects let you treat methods as values.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: