【问题标题】:Is it possible to define class methods within `class_eval`?是否可以在 `class_eval` 中定义类方法?
【发布时间】:2015-06-23 04:52:23
【问题描述】:

我知道可以使用class_eval 定义实例方法。是否可以在class_eval的上下文中定义类方法?

【问题讨论】:

    标签: ruby metaprogramming class-eval


    【解决方案1】:

    是的,有可能:

    class Foo
    end
    
    Foo.class_eval do
      def self.bar
        puts "I'm a class method defined using class_eval and self"
      end
    
      def baz
        puts "I'm an instance method defined using class_eval without self"
      end
    end
    
    Foo.bar # => "I'm a class method defined using class_eval and self"
    
    foo = Foo.new
    foo.baz # => "I'm an instance method defined using class_eval without self"
    

    据我所知,这是因为在class_eval 中,self 是 Foo 类,而执行 def Foo.bar 会创建一个类方法。

    【讨论】:

    • 你能用define_method定义吗
    【解决方案2】:
    Foo.class_eval do
      ...
    end
    

    等同于:

    class Foo
      ...
    end
    

    我们需要Module#class_eval 来操作一个包含类名的变量。例如,如果:

    klass = Foo
    

    你可以写:

    klass.class_eval do
      ...
    end
    

    而关键字class 需要一个常量。

    class_eval 在这里做了两件事:

    • 它将self 更改为klass 的值(Foo);然后它
    • “打开”klass (Foo) 的值,方法与关键字 class 相同。

    【讨论】:

      猜你喜欢
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多