4

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
1
  • It's for a SERP checker. A user enters their keywords and then when I search Google with the list of keywords, I want to be able to take the serps and put them in an array named for the keyword that was just searched. And then I can take each array and check for where their url is located in the list. I hope that explains it well enough. Commented May 23, 2011 at 5:48

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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

puts @a #[1,2,3]

2 Comments

When I run it with that, I get an undefined method or variable when I attempt to print one of the new arrays. For example, I tried: puts awesome.to_s and I get that error
@Melanie, See my updated answer. You should be able to get that to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.