是否有可能摆脱在评估下面的语句呢?下面的代码滤除其由类型BaseClass的派生的所有类。然后这些类被实例化和方法“你好”被调用。

module MySpace

  class BaseClass
    def hello; print "\nhello world"; end
  end

  class A<BaseClass
    def hello; super; print ", class A was here"; end
  end

  class B<BaseClass
    def hello; super; print ", I'm just a noisy class"; end
  end

  MySpace.constants.each do | e |
    c=eval(e)
    if c < BaseClass
      c.new.hello
    end
  end

end

所以执行后的输出是:

世界你好,我只是一个吵吵闹闹的班级结果 世界你好,类A是此处

我想的不必要的使用的 EVAL 是恶。而且我不知道,如果使用的评估是强制性这里。是有一个更聪明的方式在从调用类型的所有类“BaseClass的”动态?

有帮助吗?

解决方案

c = MySpace.const_get(e)

其他提示

EVAL是我知道的,只有这样才能把字符串转换成一常数。它甚至铁轨的方式做的: http://api.rubyonrails.com/classes/Inflector.html#M001638

在奇怪的是,常数返回字符串。

你有没有看着class_eval呢?

------------------------------------------------------ Module#class_eval
     mod.class_eval(string [, filename [, lineno]])  => obj
     mod.module_eval {|| block }                     => obj
------------------------------------------------------------------------
     Evaluates the string or block in the context of _mod_. This can be
     used to add methods to a class. +module_eval+ returns the result of
     evaluating its argument. The optional _filename_ and _lineno_
     parameters set the text for error messages.

        class Thing
        end
        a = %q{def hello() "Hello there!" end}
        Thing.module_eval(a)
        puts Thing.new.hello()
        Thing.module_eval("invalid code", "dummy", 123)

    produces:

        Hello there!
        dummy:123:in `module_eval': undefined local variable
            or method `code' for Thing:Class
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top