Ruby 有什么好办法能动态定义类吗?

richarddong · 2013年08月08日 · 最后由 blacktulip 回复于 2013年08月08日 · 2798 次阅读

除了 http://stackoverflow.com/a/6583845 这里的方法:

a_new_class = Class.new(Object) do
  attr_accessor :x

  def initialize(x)
    print #{self.class} initialized with #{x}"
    @x = x
  end
end

SomeModule.const_set("ClassName", a_new_class)

c = ClassName.new(10)

还有什么更好的方法咩?


def define_class(class_name, attribute)
  eval "
    class #{class_name}
      def #{attribute}=(value)
        raise 'Invalide attribute' unless value
        @#{attribute} = value
      end
      def #{attribute}()
        @#{attribute}
      end
    end
  "
end

以上为抄书

#2 楼 @richarddong 嗯... 我第一次看也被吓尿过 还有 method_missing 这些纯属作弊的东西...

需要 登录 后方可回复, 如果你还没有账号请 注册新账号