[英]Is it possible to define class methods within `class_eval`?
我知道可以使用class_eval
定義實例方法。 是否可以在class_eval
的上下文中定義類方法?
對的,這是可能的:
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
會創建一個類方法。
Foo.class_eval do
...
end
與以下內容相同:
class Foo
...
end
我們需要Module#class_eval來操作一個包含類名的變量。 例如,如果:
klass = Foo
你可以寫:
klass.class_eval do
...
end
而關鍵字class
需要一個常量。
這里class_eval
做了兩件事:
self
改為klass
( Foo
)的值; 然后呢 class
相同的方式“打開” klass
( Foo
)的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.