Ruby symbol to class
Solution 1
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)
Solution 2
Rails
For use with Rails only.
With a string:
"Module".constantize #=> Module
"Class".constantize #=> Class
With a symbol:
:module.to_s.classify.constantize #=> Module
:open_struct.to_s.classify.constantize #=> OpenStruct
If you are dealing with a multi-word symbol, then you'll want to add #classify
to the chain to properly handle the capitalization of all the parts of the constant.
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-constantize
Solution 3
None of the solutions I've seen work if you want to turn :foo_bar into FooBar. If that's what you're looking for:
:foo_bar.to_s.split("_").collect(&:capitalize).join.constantize
=> FooBar
hope that helps someone.
Solution 4
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
Solution 5
class Bob
end
def create(name)
return eval("#{name}.new")
end
b = create(:Bob)
puts b.class
intargc
Updated on July 28, 2022Comments
-
intargc almost 2 years
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?
-
intargc almost 15 yearsWell, thankfully I didn't ask for the "best" way, but just a way... ;)
-
Dave Sims almost 12 yearsThat's what 'camelize' is for: :foo_bar.to_s.camelize
-
Ross Allen almost 12 years@DaveSims
camelize
is an ActiveRecord extension: api.rubyonrails.org/classes/ActiveSupport/…, although so isconstantize
. -
Dave Sims almost 12 yearsYes, like Dan Frade, I should have mentioned that. :)
-
JustinStolle almost 12 yearsAre you asking a question inside of an answer? For shame! ;)
-
Joe almost 12 years@JustinStolle, I don't think its a new question, more guidance regarding to the original question? :)
-
phil pirozhkov over 11 yearsjust for the case, if
Bob
is defined in modulePeople
and you know it, you canPeople.const_get(:Bob)
-
superluminary about 11 yearsIf you're using Rails this is probably the best solution.
-
tjbp almost 8 yearsThe question specifically asks about symbols and constantize does not exist on the Symbol class in Rails. Answer should be
:Module.to_s.constantize
.