Where does `singleton` methods reside in Ruby?

有些话、适合烂在心里 提交于 2019-12-04 16:56:29

You're on the right track.

1) When looking for the method in the singleton class, you wanted to use instance_methods, not methods:

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

It is a bit confusing, since method_defined? really means "instance methods defined?", while methods really means singleton methods...

2) You can't subclass or instantiate a singleton class because it is meant to be a singleton, i.e. have exactly one instance.

It doesn't matter anyways, since you should instead use mixins for code that you want to reuse. These can be included/prepended in as many singleton classes or normal classes as you want:

foo.extend ResuableFunctionality
# or equivalently:
class << foo
  include ReusableFunctionality
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!