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
--
Posted via http://www.ruby-forum.com/\.
Or more generally,
# from Jim Weirich (based on email correspondence)
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:
# File vendor/rails/activesupport/lib/active_support/inflector.rb, 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
Rob Biedenharn http://agileconsultingllc.com
Rob@AgileConsultingLLC.com
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