How to Use send Method in Ruby: Syntax and Examples
In Ruby,
send lets you call a method on an object by its name as a symbol or string, even if the method is private. You use it like object.send(:method_name, args) to invoke the method dynamically.Syntax
The send method calls another method on an object using the method's name as a symbol or string. You can also pass arguments to the method being called.
- object: The instance you want to call a method on.
- send: The Ruby method that invokes another method dynamically.
- method_name: The name of the method to call, given as a symbol or string.
- args: Optional arguments to pass to the method.
ruby
object.send(:method_name, arg1, arg2)
Example
This example shows how to use send to call a public method and a private method dynamically on an object.
ruby
class Person def greet(name) "Hello, #{name}!" end private def secret "This is a secret message." end end person = Person.new puts person.send(:greet, "Alice") puts person.send(:secret)
Output
Hello, Alice!
This is a secret message.
Common Pitfalls
Common mistakes when using send include:
- Using
sendwith user input without validation can cause security risks by calling unintended methods. - Trying to call methods that do not exist will raise a
NoMethodError. - For safer calls that respect method visibility, use
public_sendinstead ofsend.
ruby
class Example def hello "Hi!" end end obj = Example.new # Wrong: calling a non-existent method # obj.send(:bye) # Raises NoMethodError # Safer: use public_send to avoid calling private methods obj.public_send(:hello) # Works # obj.public_send(:private_method) # Raises NoMethodError if private
Quick Reference
| Method | Description |
|---|---|
| send(:method_name, *args) | Calls any method, including private ones, with arguments. |
| public_send(:method_name, *args) | Calls only public methods, respecting visibility. |
| respond_to?(:method_name) | Checks if the object has the method before calling. |
Key Takeaways
Use
send to call methods dynamically by name, including private methods.Always validate method names if they come from user input to avoid security risks.
Use
public_send to call only public methods safely.Calling a non-existent method with
send raises a NoMethodError.Check if an object responds to a method with
respond_to? before using send.