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']
variable开发者_如何学运维s.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:
variables = ['awesome', 'fantastic', 'neato']
hash = variables.each_with_object({ }) { |k, h| h[k] = [ ] }
Or, if you don't have each_with_object
:
hash = variables.inject({ }) { |h, k| h[k] = [ ]; h }
Note the argument order switch in the block with inject
and that you have to return h
from 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 variables
end up being non-alphanumeric.
arr = ['a', 'b', 'c']
arr.each do |a|
self.instance_variable_set(('@' + a.to_s).intern, [1,2,3])
}
puts @a #[1,2,3]
精彩评论