rubysingleton-methods

Are all singleton methods public?


Is a singleton method necessarily public? If not, when would a private/protected singleton method be useful?


Solution

  • Singleton methods do not necessarily need to be public. Private/protected singleton methods are useful in the same situations as regular private/protected methods - for example as a helper method that you do not intend to be called outside of the class.

    class Foo
    end
    
    f = Foo.new
    
    class << f
      def foo
        helper
        # other stuff
      end
    
      private
      def helper
      end
    end