Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array names programmatically in Ruby

Tags:

arrays

ruby

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
like image 206
Melanie Shebel Avatar asked Dec 10 '22 08:12

Melanie Shebel


2 Answers

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.

like image 176
mu is too short Avatar answered Dec 21 '22 22:12

mu is too short


arr = ['a', 'b', 'c']
arr.each do |a|
  self.instance_variable_set(('@' + a.to_s).intern, [1,2,3])
}

puts @a #[1,2,3]
like image 20
Jacob Relkin Avatar answered Dec 21 '22 23:12

Jacob Relkin