How to create a private class method?

后端 未结 8 1316
北荒
北荒 2020-12-02 04:43

How come this approach of creating a private class method works:

class Person

  def self.get_name
    persons_name
  end

  class << self

    private         


        
8条回答
  •  既然无缘
    2020-12-02 05:02

    By default all class methods are public. To make them private you can use Module#private_class_method like @tjwallace wrote or define them differently, as you did:

    class << self
    
      private
    
      def method_name
        ...
      end
    end
    

    class << self opens up self's singleton class, so that methods can be redefined for the current self object. This is used to define class/module ("static") method. Only there, defining private methods really gives you private class methods.

提交回复
热议问题