是否可以在 class_eval 中定义类方法?

And*_*imm 5 ruby metaprogramming class-eval

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

And*_*imm 4

对的,这是可能的:

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"
Run Code Online (Sandbox Code Playgroud)

据我所知,这是因为class_eval,内self是 Foo 类,并且这样做def Foo.bar会创建一个类方法。