Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string in Ruby variable name?

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?

like image 948
Tim Avatar asked Dec 17 '22 07:12

Tim


2 Answers

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.).

like image 152
Jordan Running Avatar answered Dec 30 '22 21:12

Jordan Running


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.

like image 36
oozzal Avatar answered Dec 30 '22 21:12

oozzal