How to use string in Ruby variable name?

I have a string that I want to use as part of the variable name. In particular, in Rails route routes:

<%= 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?

+4
source share
2 answers

Sure:

 lol = 'foo' send "#{lol}_path" # or send lol + '_path' 

Explanation: Object#send sends this method (that is, "calls" the method) to the receiver. As with any method call, without an explicit receiver (for example, some_object.send 'foo' ), the current context becomes the receiver, so calling send :foo equivalent to self.send :foo . In fact, Rails often uses this technique behind the scenes ( for example ).

+9
source

Something else!

 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 happens here:
p.send "some_method" calls p.some_method , and the surrounding circle makes the chain possible, i.e. calls p.pet.make_noise at the end. I hope I get it.

+2
source

Source: https://habr.com/ru/post/1381430/


All Articles