Is it possible to convert a String into a Class id?
Something like ‘Array’.to_class.new
Is it possible to convert a String into a Class id?
Something like ‘Array’.to_class.new
Roberto Eduardo Decurnex Gorosito wrote:
Is it possible to convert a String into a Class id?
Something like ‘Array’.to_class.new
Object.const_get(“Array”).new
Wolfgang Nádasi-Donner
On Feb 4, 2008, at 2:30 PM, Wolfgang Nádasi-Donner wrote:
Roberto Eduardo Decurnex Gorosito wrote:
Is it possible to convert a String into a Class id?
Something like ‘Array’.to_class.new
Object.const_get(“Array”).new
Wolfgang Nádasi-Donner
Or more generally,
def constantize(camel_cased_word)
camel_cased_word.
sub(/^::/,‘’).
split(“::”).
inject(Object) { |scope, name| scope.const_get(name) }
end
Also, you can see how ActiveSupport does it for Rails:
line 245
245: def constantize(camel_cased_word)
246: unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
247: raise NameError, “#{camel_cased_word.inspect} is not a valid
constant name!”
248: end
249:
250: Object.module_eval(“::#{$1}”, FILE, LINE)
251: end
-Rob
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs