I’m a noob programmer and am wondering how to create array names using a list of words from another array.
For example, I would like to take this array:
array = ['fruits','veggies']
and turn it into something like this:
fruits = []
veggies = []
What is the best way to do this in Ruby?
Here is my shot at it, where I failed miserably:
variables = ['awesome', 'fantastic', 'neato']
variables.each do |e|
e = []
e << [1, 2, 3]
end
puts neato
The problem is that your array might contain a value that matches the name of a local variable or method and that’s when the pain and confusion starts.
Probably best to build a hash of arrays instead:
Or, if you don’t have
each_with_object:Note the argument order switch in the block with
injectand that you have to returnhfrom the block.This way you have your arrays but you also protect your namespace by, essentially, using a hash as little portable namespace. You can create variables on the fly as Jacob Relkin demonstrates but you’re asking for trouble by doing it that way. You can also run into trouble if the elements of
variablesend up being non-alphanumeric.