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:
Explanation:
Object#sendsends 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 callingsend :foois equivalent toself.send :foo. In fact Rails uses this technique behind the scenes quite a lot (e.g.).