Ge Bro wrote:
> Hey all,
> this is a total newbie question, i'm just starting to learn Ruby.
> 
> here's the thing: i've got a couple of arrays with several items in
> each. I'd like to use a block to iterate through each array, and create
> objects of the class that is named the same as the array.
> 
> This is supposed to populate a database where tables are named after
> arrays, and each table contains 1 column called "item_name" with items
> from the corresponding array.
> 
> allow me to illustrate:
> 
> ###
> 
> some_item = ['foo', 'bar']
> other_item = ['alpha', 'bravo', 'foxtrot', 'zebra']
> 
> ['some_item', 'other_item'].each do |this_array|
>   array_length = 0
>   this_object = this_array.to_s.capitalize   #<== here's the problem
>   until array_length == this_array.length
>     this_object.new(:item_name => this_array[array_length])
>     array_length += 1
>   end
> end
> 
> ###
> 
> the problem is, this_object becomes a string with the value of
> |this_array|. How do I explain to the program that its value is not just 
> a string, but actually a name of the class, an instance of which i'm
> trying to initialize?
> 
> Forgive the dumb question, but i'm just starting out. I've been banging
> my head against this for hours.... any help would be appreciated...
> 
> thanks!

By the way, are you aware that your arrays can contain the class objects 
themselves rather than strings:

class Dog
  def id
    puts "I'm a Dog"
  end
end

class Flower
  def id
    puts "I'm a Flower"
  end
end

class Circle
  def id
    puts "I'm a Circle"
  end
end

arr = [Dog, Flower, Circle]

arr.each do |a_class|
  obj = a_class.new
  obj.id
end

--output:--
I'm a Dog
I'm a Flower
I'm a Circle



-- 
Posted via http://www.ruby-forum.com/.