Ruby symbol to class Ruby symbol to class ruby ruby

Ruby symbol to class


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)


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


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.