Ruby жжёт!!

By 0slice

Вот вопрос 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).

8 коммент. на “Ruby жжёт!!”

  1. Art:

    Спасибо, жду новых статей.

  2. Аверьян:

    Больше бумаги – жопа чище.

  3. Автоном:

    В ереване давно нет презервативов. Сколько можно работать без них?

  4. Лиана:

    Вот у меня еще с детства ребенок появился.

  5. Ипат:

    Буду писать прямо, причем по национальности я грузин.

  6. Buglet:

    Баба с возу – кобыла в позу…

  7. Anton:

    Без техники безопасности в половом акте не обайдешься.

  8. Ия:

    Приятно узнать что думает по этому поводу умный человек. Спасибо за статью.

Ответить