Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically create a local variable in Ruby?

Tags:

ruby

irb

I am trying to dynamically create local variables in Ruby using eval and mutate the local-variables array. I am doing this in IRB.

eval "t = 2"
local_variables # => [:_]
eval "t"
# => NameError: undefined local variable or method `t' for main:Object
local_variables << "t".to_sym # => [:_, :t]
t
# => NameError: undefined local variable or method `t' for main:Object
like image 890
ppone Avatar asked Jul 24 '13 19:07

ppone


People also ask

How do you create a local variable in Ruby?

Local Variables: A local variable name always starts with a lowercase letter(a-z) or underscore (_). These variables are local to the code construct in which they are declared. A local variable is only accessible within the block of its initialization. Local variables are not available outside the method.

What is dynamic local variable?

In a high-level language, non-static local variables declared in a function are stack dynamic local variables by default. Some C++ texts refer to such variables as automatics. This means that the local variables are created by allocating space on the stack and assigning these stack locations to the variables.

How do you avoid global variables in Ruby?

When in need of a global variable, you can always define a constant in the main name space. Mutable objects like string, hash, array can be modified even if it is a constant.

Should you use global variables in Ruby?

Global variables should be used sparingly. They are dangerous because they can be written to from anywhere. Overuse of globals can make isolating bugs difficult; it also tends to indicate that the design of a program has not been carefully thought out.


3 Answers

You have to synchronize the evaluations with the same binding object. Otherwise, a single evaluation has its own scope.

b = binding
eval("t = 2", b)
eval("local_variables", b) #=> [:t, :b, :_]
eval("t", b) # => 2
b.eval('t') # => 2
like image 83
sawa Avatar answered Oct 22 '22 10:10

sawa


You have to use the correct binding. In IRB for example this would work:

irb(main):001:0> eval "t=2", IRB.conf[:MAIN_CONTEXT].workspace.binding
=> 2
irb(main):002:0> local_variables
=> [:t, :_]
irb(main):003:0> eval "t"
=> 2
irb(main):004:0> t
=> 2
like image 27
Stefan Avatar answered Oct 22 '22 12:10

Stefan


You could set instance variables like this:

instance_variable_set(:@a, 2)
@a
#=> 2
like image 37
Patrick Oscity Avatar answered Oct 22 '22 10:10

Patrick Oscity