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

richarddong · August 08, 2013 · Last by blacktulip replied at August 08, 2013 · 2800 hits

除了 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

以上为抄书

#1 楼 @blacktulip 这。。。也行哈~

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

You need to Sign in before reply, if you don't have an account, please Sign up first.