Вот вопрос 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).
Январь 27, 2009 в 5:49 пп |
Спасибо, жду новых статей.
Март 3, 2009 в 1:58 дп |
Больше бумаги – жопа чище.
Март 6, 2009 в 2:02 дп |
В ереване давно нет презервативов. Сколько можно работать без них?
Апрель 12, 2009 в 2:16 дп |
Вот у меня еще с детства ребенок появился.
Апрель 18, 2009 в 3:33 пп |
Буду писать прямо, причем по национальности я грузин.
Апрель 19, 2009 в 2:25 дп |
Баба с возу – кобыла в позу…
Апрель 19, 2009 в 8:03 пп |
Без техники безопасности в половом акте не обайдешься.
Сентябрь 20, 2009 в 3:02 дп |
Приятно узнать что думает по этому поводу умный человек. Спасибо за статью.