哪里`singleton`方法驻留在红宝石?(Where does `singleton` meth

2019-08-17 15:56发布

我用打singleton class在我的IRB。 而这样做尝试下面的代码片段。

class Foo ; end
#=> nil
foo = Foo.new
#=> #<Foo:0x2022738>

foo.define_singleton_method(:bar , method(:puts))
#=> #<Method: Object(Kernel)#puts>

在这里我上面刚刚创建了一个singleton的类的实例方法Foo

foo.bar("hi")
hi
#=> nil
foo.singleton_methods
#=> [:bar]

foo_sing = foo.singleton_class
#=> #<Class:#<Foo:0x2022738
foo_sing.is_a? Class
#=> true
foo_sing.instance_of? Class
#=> true
foo_sing.inspect
#=> "#<Class:#<Foo:0x1e06dc8>>"

在上面我试图创建一个singleton class的类的实例Foo 。 如果还测试foo_sing持有参照singleton class的类的实例Foo

foo_sing.methods(false)
#=> []
foo_sing.methods.include? :bar
#=> false

在上面我一直在寻找,如果singleton_method bar是在foo_sing或not.But发现它不存在there.Then我的问题是- 哪里那些singleton_method居住在红宝石?

foo_sing.new.methods(false)
#TypeError: can't create instance of singleton class
#        from (irb):10:in `new'
#        from (irb):10
#        from C:/Ruby193/bin/irb:12:in `<main>'
class Bas < foo_sing ; end
#TypeError: can't make subclass of singleton class
#        from (irb):16
#        from C:/Ruby193/bin/irb:12:in `<main>'

在上面的部分我被检查,如果我们可以创建,实例singleton class或不和的子类singleton class ,像普通类。 但问题的答案,我发现是NO。 背后是什么概念或理论或目的是什么?

再在下面的代码中,我可以看到被覆盖的内部的同名方法, singleton class 。 但是,当我搜索类中该方法没有找到我上面问。

class Foo ; end
#=> nil
foo = Foo.new
#=> #<Foo:0x225e3a0>

def foo.show ; puts "hi" ; end
#=> nil

foo.show
#hi
#=> nil

class << foo ;def show ; puts "hello" ; end ;end
#=> nil

foo.show
#hello
#=> nil

Answer 1:

你在正确的轨道上。

1)当寻找单身类中的方法,你想用instance_methods ,没有methods

foo_sing.instance_methods.include? :bar # => true
# or
foo_sing.method_defined? :bar # => true

这是一个有点混乱,因为method_defined? 真正的意思是“实例的方法定义的?”,而methods实际上意味着singleton methods ...

2)你不能继承或实例化一个单例类,因为它意味着是一个单身,即有一个确切的实例。

它不反正无所谓,因为你应该使用要重用代码的混入。 这些可以包含/前置在尽可能多的单身类或正常类,只要你想:

foo.extend ResuableFunctionality
# or equivalently:
class << foo
  include ReusableFunctionality
end


文章来源: Where does `singleton` methods reside in Ruby?