String to Class

  • Thread starter Roberto Eduardo Decurnex Gorosito
  • Start date
R

Roberto Eduardo Decurnex Gorosito

[Note: parts of this message were removed to make it a legal post.]

Is it possible to convert a String into a Class id?

Something like 'Array'.to_class.new
 
W

Wolfgang Nádasi-Donner

Roberto said:
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
 
R

Rob Biedenharn

Object.const_get("Array").new

Wolfgang N=E1dasi-Donner

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, =20
line 245
245: def constantize(camel_cased_word)
246: unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =3D~ =
camel_cased_word
247: raise NameError, "#{camel_cased_word.inspect} is not a valid =20=

constant name!"
248: end
249:
250: Object.module_eval("::#{$1}", __FILE__, __LINE__)
251: end

-Rob

Rob Biedenharn http://agileconsultingllc.com
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Converting an Array to a String in JavaScript 7
Splitting on capital letters 12
string to int 6
Variable name to string 4
gsub for string 3
Class extension 0
Product Class 3
Avoiding eval 5

Members online

Forum statistics

Threads
473,815
Messages
2,569,705
Members
45,494
Latest member
KandyFrank

Latest Threads

Top