What does send()
do in Ruby, and how is it used?
Can someone explain what the following snippet does?
obj.send("#{method_name}")
How does Ruby send work, and in what scenarios is it useful?
What does send()
do in Ruby, and how is it used?
Can someone explain what the following snippet does?
obj.send("#{method_name}")
How does Ruby send work, and in what scenarios is it useful?
send()
in Ruby is used to call a method dynamically by its name as a string or symbol. Instead of calling a method directly like obj.some_method, you can use obj.send(:some_method), which is particularly useful when the method name is stored in a variable.
For example:
class Greeting
def hello
"Hello, world!"
end
end
g = Greeting.new
puts g.send(:hello) # Outputs "Hello, world!"
This is the same as calling g.hello, but send lets you choose the method dynamically.
Using send() with Arguments : Another important use case for send() is when a method takes arguments. You can pass arguments after the method name:
class MathOperations
def add(a, b)
a + b
end
end
math = MathOperations.new
puts math.send(:add, 2, 3) # Outputs 5
This can be helpful when you don’t know beforehand which method needs to be called, such as when dynamically invoking methods in metaprogramming or when processing user input.
Both explanations are spot on! However, one thing to keep in mind is that send()
can also invoke private methods, which isn’t always desirable:
class Secret
private
def hidden_message
"This is private!"
end
end
s = Secret.new
puts s.send(:hidden_message) # Works, but bypasses privacy!
If you want to ensure only public methods are called, use public_send()
instead:
s.public_send(:hidden_message) # Will raise an error since it's private
This makes the code safer and prevents accidentally calling internal methods.