views:

776

answers:

4

Is there a way in Ruby to take a symbol or string and turn it into a class of the same name?

For instance, if I have a class such as

class Bob
  def talk
     puts "Hi, I'm bob"
  end
end

And a method I have somewhere else in the code is passed a symbol :bob, can I in some way turn that into the class Bob? Maybe something like

b = :Bob.new
b.talk

Or is there a way to do something similar to this?

+1  A: 

NameSpace.const_get(classname) will return the class object (assuming that classname contains the name of a class - if it contains the name of a constant that is not a class, it will return the value of that constant). The toplevel namespace is Object, so you can do Object.const_get(:Bob).new

sepp2k
A: 
class Bob
end

def create(name)
  return eval("#{name}.new")
end

b = create(:Bob)
puts b.class
Tim Hoolihan
+4  A: 

http://rails.rubyonrails.org/classes/Inflector.html#M001638

  "Module".constantize #=> Module
  "Class".constantize #=> Class
Dan Frade
Sorry, I should probably add that this is a Rails only thing.
Dan Frade
+10  A: 

There are many ways to do this. Your lack of context makes it impossible to elect a "best" way. Here's a few ayways.

Kernel.const_get(:Bob)

eval(:Bob.to_s)

Kernel.const_get(:bob.to_s.capitalize)
August Lilleaas
Well, thankfully I didn't ask for the "best" way, but just a way... ;)
intargc