Reputation: 19506
I would like to get an object's class and turn it into a symbol. In particular, given this:
class Apple
end
class Apple_Pie
def name
"apple pies"
end
end
fruit_table = {:Apple => :Apple_Pie}
a = Apple.new
I would like to get an instance of the class Apple_Pie
starting from a
. I tried:
obj = Object.const_get(fruit_table[a.class])
obj.name
expecting
apple pies
but this doesn't actually happen. I am not sure how to turn the class into a symbol. Any ideas?
Upvotes: 1
Views: 1767
Reputation: 1013
I just pasted your code, and add .new to `obj = obj = Object.const_get(fruit_table[a.class.name.to_sym]).new.name It worked. Not sure if this is actually what you wanted though.
update: forgot to add .name.to_sym
Upvotes: 1
Reputation: 26488
You need to use Module#name
to get the string name of the class, then cast it to a symbol using String#to_sym
.
From my console:
> a.class
=> Apple
> a.class.name
=> "Apple"
> a.class.name.to_sym
=> :Apple
Upvotes: 5