0
0
Rubyprogramming~5 mins

Send for calling methods dynamically in Ruby

Choose your learning style9 modes available
Introduction

Sometimes, you want to call a method when you only know its name during the program. send helps you do that easily.

You want to call different methods based on user input.
You need to run a method whose name is stored in a variable.
You want to avoid writing many if-else statements for method calls.
You want to make your code flexible and reusable.
You want to call private methods from outside the class (careful!).
Syntax
Ruby
object.send(:method_name, arg1, arg2, ...)

object is where the method lives.

:method_name is a symbol or string of the method's name.

Examples
Calls the upcase method on the string name dynamically.
Ruby
name = "hello"
puts name.send(:upcase)
Calls the greet method with argument "Alice" dynamically.
Ruby
class Greeter
  def greet(name)
    "Hello, #{name}!"
  end
end

g = Greeter.new
puts g.send(:greet, "Alice")
Calls the method add dynamically using a variable holding the method name.
Ruby
def add(a, b)
  a + b
end

method_name = :add
puts send(method_name, 5, 3)
Sample Program

This program creates a calculator object and calls the multiply method dynamically using send. It prints the result.

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

  def multiply(a, b)
    a * b
  end
end

calc = Calculator.new
method_to_call = :multiply
result = calc.send(method_to_call, 4, 5)
puts "Result: #{result}"
OutputSuccess
Important Notes

Be careful when using send with user input to avoid security risks.

send can call private methods, so use it wisely.

Summary

send lets you call methods when you only know their names during the program.

It makes your code flexible and helps avoid many if-else statements.

Use symbols or strings for method names, and pass arguments after the method name.