I have a string that I want to use as part of a variable name. Specifically, in Rails route paths:
<%= foo_path %>
<%= bar_path %>
I want the first part of the route name to be dynamic. So something like
@lol = "foo"
<%= [@lol]_path %> # <-- This would really be the "foo_path" variable
Can Ruby do this?
Sure:
lol = 'foo'
send "#{lol}_path"
# or
send lol + '_path'
Explanation: Object#send
sends the method to (i.e. "calls" the method on) the receiver. As with any method call, without an explicit receiver (e.g. some_object.send 'foo'
) the current context becomes the receiver, so calling send :foo
is equivalent to self.send :foo
. In fact Rails uses this technique behind the scenes quite a lot (e.g.).
Something more!
class Person
attr_accessor :pet
end
class Pet
def make_noise
"Woof! Woof!"
end
end
var_name = "pet"
p = Person.new
p.pet = Pet.new
(p.send "#{var_name}").make_noise
So what's happening here is:p.send "some_method"
calls p.some_method
and the parenthesis surrounding makes the chaining possible i.e. call p.pet.make_noise
in the end. Hope I'm clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With