Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a local variable?

Tags:

ruby

I have a variable var = "some_name" and I would like to create a new object and assign it to some_name. How can I do it? E.g.

var = "some_name" some_name = Struct.new(:name) # I need this a = some_name.new('blah') # so that I can do this. 
like image 382
Bala Avatar asked Aug 31 '13 21:08

Bala


People also ask

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 create a local variable?

Right-click an existing front panel object or block diagram terminal and select Create»Local Variable from the shortcut menu to create a local variable. A local variable icon for the object appears on the block diagram. You also can select a local variable from the Functions palette and place it on the block diagram.

How do you create a dynamic variable name in python?

Use a Dictionary to Create a Dynamic Variable Name in Python It is written with curly brackets {} . In addition to this, dictionaries cannot have any duplicates. A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.

Where are dynamic created variables stored?

Dynamically allocated variables live in a piece of memory known as the heap, these are requested by the running program using the keyword "new". A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer.


1 Answers

You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval):

eval 'foo = "bar"' foo  # NameError: undefined local variable or method `foo' for main:Object 

They can be used within the eval-ed code itself, though:

eval 'foo = "bar"; foo + "baz"' #=> "barbaz" 

Ruby 2.1 added local_variable_set, but that cannot create new local variables either:

binding.local_variable_set :foo, 'bar' foo # NameError: undefined local variable or method `foo' for main:Object 

This behavior cannot be changed without modifying Ruby itself. The alternative is to instead consider storing your data within another data structure, e.g. a Hash, instead of many local variables:

hash = {} hash[:my_var] = :foo 

Note that both eval and local_variable_set do allow reassigning an existing local variable:

foo = nil eval 'foo = "bar"' foo  #=> "bar" binding.local_variable_set :foo, 'baz' foo  #=> "baz" 
like image 183
Andrew Marshall Avatar answered Sep 28 '22 09:09

Andrew Marshall