context: I'm currently working with the parser gem and trying to handle all cases of what is a public method.
I've written this next code, hoping it will fail on runtime. But it doesn't.
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
Run Code Online (Sandbox Code Playgroud)
So I'm wondering where is met callable (Foo.met would raise a NoMethodError)? And is this a useful Ruby pattern or just something I should not do, neither care about?
Ruby中的每个对象都有其自己的单例类。这是定义所有实例方法的地方。
考虑以下示例。
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/
#? []
Run Code Online (Sandbox Code Playgroud)
需要Singleton类才能扩展对象等。
在Ruby中,一切都是object。类的确也是对象。这就是每个类都有自己的单例类的原因。每个单例类都有其单例类。
c1.singleton_class.singleton_class.singleton_class.singleton_class
#? #<Class:#<Class:#<Class:#<Class:#<C:0x000055cb0459c700>>>>>
Run Code Online (Sandbox Code Playgroud)
定义上的方法foo是存储在单例类的foo。在foo的singleton类上定义的方法存储在的singleton类的singleton类中foo。依此类推。
它不是很实用,但是由于Ruby如何将所有内容都视为,因此仍有可能Object。
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |