Архив рубрики ‘ruby’

Ruby жжёт!!

Январь 22, 2007

Вот вопрос http://www.ruby-forum.com/topic/94078
вот ответ:
11.3.3. Dynamically Instantiating a Class by Name
We have seen this question more than once. Given a string containing the name of a class, how can we create an instance of that class?

The proper way is with const_get, which we just saw. All classes in Ruby are normally named as constants in the «global» namespacethat is, members of Object.

classname = «Array»

klass = Object.const_get(classname)
x = klass.new(4, 1) # [1, 1, 1, 1]

What if the names are nested? It turns out this doesn’t work:

class Alpha
class Beta
class Gamma
FOOBAR = 237
end
end
end

str = «Alpha::Beta::Gamma::FOOBAR»
val = Object.const_get(str) # error!

This is because const_get just isn’t «smart» enough to recognize nested names of this sort. The following example is an idiom that will work well, however:

# Same class structure

str = «Alpha::Beta::Gamma::FOOBAR»
val = str.split(«::»).inject(Object) {|x,y| x.const_get(y) } # 237

This is a commonly needed piece of code (and a neat use of inject).