0
0
Rubyprogramming~5 mins

Method objects with method() in Ruby

Choose your learning style9 modes available
Introduction

Method objects let you save a method as a value. This helps you call the method later or pass it around like a regular object.

When you want to store a method to call it multiple times later.
When you want to pass a method as an argument to another method.
When you want to delay running a method until a certain event happens.
When you want to keep your code organized by separating method calls.
When you want to use the same method in different places without repeating code.
Syntax
Ruby
method_object = object.method(:method_name)

The method call returns a Method object representing the method.

You use a symbol (like :method_name) to specify the method name.

Examples
This saves the upcase method of the string "hello" into m. Calling m.call runs upcase and prints HELLO.
Ruby
str = "hello"
m = str.method(:upcase)
puts m.call
This saves the method greet as a Method object and calls it with "Alice".
Ruby
def greet(name)
  "Hi, #{name}!"
end

m = method(:greet)
puts m.call("Alice")
This stores the sum method of the array and calls it to print the total 6.
Ruby
arr = [1, 2, 3]
method_obj = arr.method(:sum)
puts method_obj.call
Sample Program

This program creates a Calculator object, saves its add method as a Method object, then calls it with two numbers and prints the sum.

Ruby
class Calculator
  def add(a, b)
    a + b
  end
end

calc = Calculator.new
add_method = calc.method(:add)

result = add_method.call(5, 7)
puts "The sum is: #{result}"
OutputSuccess
Important Notes

You can call the method object with call and pass any needed arguments.

Method objects keep the original method's context, so they remember which object they belong to.

Using method objects can make your code more flexible and easier to reuse.

Summary

Method objects let you treat methods like values you can save and pass around.

Use object.method(:name) to get a Method object.

Call the method later with call and arguments.