class 方法 `self.` 在 class 方法块 `class << self` 在 Ruby
class method `self.` within class methods block `class << self` in Ruby
上下文: 我目前正在使用 parser gem 并尝试处理所有 什么是 public方法.
我已经编写了下一段代码,希望它会在运行时失败。但事实并非如此。
class Foo
class << self
def self.met
puts "I'm just a troll"
end
class << self
def mut
puts "Try and find me"
end
end
end
end
所以我想知道 met
在哪里可以调用(Foo.met
会引发 NoMethodError
)?这是一个有用的 Ruby 模式还是我不应该做的事情,两者都不关心?
Ruby 中的每个对象都有自己的 singleton class。这是定义所有实例方法的地方。
考虑以下示例。
class C; end
c1, c2 = C.new, C.new
c1.extend(Module.new { def m1; 42; end })
c1.m1
#⇒ 42
c2.m1
#⇒ NoMethodError: undefined method `m1' for #<C:0x000055cb062e6888>
c1.singleton_class.instance_methods.grep /m1/
#⇒ [:m1]
c2.singleton_class.instance_methods.grep /m1/
#⇒ []
需要单例 class 才能扩展对象等
在Ruby中,一切都是对象。 类 确实也是对象。这就是为什么每个 class 都有自己的单例 class。每个单例 class 都有它的单例 class.
c1.singleton_class.singleton_class.singleton_class.singleton_class
#⇒ #<Class:#<Class:#<Class:#<Class:#<C:0x000055cb0459c700>>>>>
在 foo
上定义的方法存储 在 foo
的单例 class 中。在foo
的单例class上定义的方法在foo
的单例class的单例class中存储 .等等。
这不是很实用,但由于 Ruby 如何将所有内容都视为 Object
,所以它仍然是可能的。
上下文: 我目前正在使用 parser gem 并尝试处理所有 什么是 public方法.
我已经编写了下一段代码,希望它会在运行时失败。但事实并非如此。
class Foo
class << self
def self.met
puts "I'm just a troll"
end
class << self
def mut
puts "Try and find me"
end
end
end
end
所以我想知道 met
在哪里可以调用(Foo.met
会引发 NoMethodError
)?这是一个有用的 Ruby 模式还是我不应该做的事情,两者都不关心?
Ruby 中的每个对象都有自己的 singleton class。这是定义所有实例方法的地方。
考虑以下示例。
class C; end
c1, c2 = C.new, C.new
c1.extend(Module.new { def m1; 42; end })
c1.m1
#⇒ 42
c2.m1
#⇒ NoMethodError: undefined method `m1' for #<C:0x000055cb062e6888>
c1.singleton_class.instance_methods.grep /m1/
#⇒ [:m1]
c2.singleton_class.instance_methods.grep /m1/
#⇒ []
需要单例 class 才能扩展对象等
在Ruby中,一切都是对象。 类 确实也是对象。这就是为什么每个 class 都有自己的单例 class。每个单例 class 都有它的单例 class.
c1.singleton_class.singleton_class.singleton_class.singleton_class
#⇒ #<Class:#<Class:#<Class:#<Class:#<C:0x000055cb0459c700>>>>>
在 foo
上定义的方法存储 在 foo
的单例 class 中。在foo
的单例class上定义的方法在foo
的单例class的单例class中存储 .等等。
这不是很实用,但由于 Ruby 如何将所有内容都视为 Object
,所以它仍然是可能的。