tags:

views:

197

answers:

4

how to convert the string "User" to User ?

+7  A: 

You can use the Module#const_get method. Example:

irb(main):001:0> ARGV
=> []
irb(main):002:0> Kernel.const_get "ARGV"
=> []
Chris Jester-Young
A: 

You can just do:

eval("User")
ehsanul
Don't use `eval` here, because: **1)** `eval` is 4 times slower than `const_get` (16 times slower in 1.9); **2)** `eval` is more easily abused if the string is from an untrusted source; **3)** `eval` is not primarily intended to retrieve a constant (`const_get` is).
molf
its evil, but I can't find another way to do it. I'm trying to constantize Logger::DEBUG in an options hash. like @psyho says, Kernel.const_get fails and I don't have ActivateState loaded.if you have another way that doesn't use Eval, would love to hear it.
coffeepac
Tried `Logger.const_get` ?
ehsanul
+2  A: 

If you have ActiveSupport loaded (e.g. in Rails) you can use

"User".constantize
severin
+2  A: 

The best way is to use ActiveSupport's constantize:

'User'.constantize

The Kernel's const_get would work also, but only if you do not have namespaced constants, so something like this:

Kernel.const_get('Foobar::User')

will fail. So if you want a generic solution, you'd be wise to use the ActiveSupport approach:

def my_constantize(class_name)
  unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ class_name
    raise NameError, "#{class_name.inspect} is not a valid constant name!"
  end

  Object.module_eval("::#{$1}", __FILE__, __LINE__)
end
psyho