MxLDevs
MxLDevs

Reputation: 19506

Ruby class to symbol

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

Answers (3)

Martin Vahi
Martin Vahi

Reputation: 139

    ob_demoobject=Hash.new
    sym=ob_demoobject.class.to_s.to_sym

Upvotes: 0

tackleberry
tackleberry

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

Douglas F Shearer
Douglas F Shearer

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

Related Questions