← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 6 of 6

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:

  1. Method Objects
Syntax
ruby
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

markup
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
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
  1. Writing method(square) without the colon, which calls square right away instead of getting the Method object; use method(:square).
  2. Using &method(:square) without the &, so map gets the Method as an argument, not a block.
  3. Expecting the Method object to change when the method is redefined.
Chapter Summary
  • Blocks and yield pass 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.