views:

36

answers:

2

So I have a class like this:

def Word


end 

and im looping thru an array like this

array.each do |value|

end

And inside that loop I want to instantiate an object, with a handle of the var

value = Word.new

Im sure there is an easy way to do this - I just dont know what it is!

Thanks!

+2  A: 

To assign things to a dynamic variable name, you need to use something like eval:

array.each do |value|
  eval "#{value} = Word.new"
end

but check this is what you want - you should avoid using eval to solve things that really require different data structures, since it's hard to debug errors created with eval, and can easily cause undesired behaviour. For example, what you might really want is a hash of words and associated objects, for example

words = {}    
array.each do |value|
  words[value] = Word.new
end

which won't pollute your namespace with tons of Word objects.

Peter
Absolutely don't do the first one unless you want to cause yourself a lot of extra trouble.
Chuck
Ahh thanks Peter and Chuck. I didn't think of doing it that way. Yes Ill stick with the second one - it looks alot smarter and actually will allow me to do more. I just needed a way to have each of my "values" (which are vars) to be a Word object. A hash of values wouldnt work because I needed methods as well as values. So A hash of Objects - brillant - thanks guys!
RetroNoodle
+2  A: 

Depending on the data structure you want to work with, you could also do this:

# will give you an array:
words = array.map { |value| Word.new(value) }

# will give you a hash (as in Peter's example)
words = array.inject({}) { |hash, value| hash.merge value => Word.new }

# same as above, but more efficient, using monkey-lib (gem install monkey-lib)
words = array.construct_hash { |value| [value, Word.new ] }