Ruby: setting a global variable by name

I am trying to dynamically set (not create, it must already exist) a global ruby โ€‹โ€‹variable in a method. The variable name is determined from the transmitted character. I am currently doing the following:

def baz(symbol) eval("$#{symbol}_bar = 42") end $foo_bar = 0 baz(:foo) puts $foo_bar # => 42 

But for me, this feeling is very bad. Is this a way to do this? Or can it be done differently? Also, I don't know how evals perform in ruby. It works much slower than

 $foo_bar = 42 
+4
source share
2 answers

If you can use an instance variable instead, there is Object#instance_variable_set .

  def baz(symbol) instance_variable_set("@#{symbol}_bar", 42) end 

Note that it only accepts variable names that can be accepted as an instance variable (starting with @ ). If you put anything else in the first argument, it will return an error. For a global variable similar to this, here is discussed: Forum: Ruby

In any case, you also have a problem with accessing the variable. How are you going to do this?

+1
source

The method looks good to me. This guy says that the effectiveness of eval is much worse, although the position is 3 years.

I will point out that this method assumes that you have many global variables, which is usually the smell of code if the code base is significant.

+2
source

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


All Articles