ruby - How to create a private class method? -


how come approach of creating private class method works:

class person    def self.get_name     persons_name   end    class << self      private      def persons_name       "sam"     end   end end  puts "hey, " + person.get_name puts "hey, " + person.persons_name  #=> raises "private method `persons_name' called person:class (nomethoderror)" 

but not:

class person    def self.get_name     persons_name   end    private    def self.persons_name     "sam"   end end  puts "hey, " + person.get_name puts "hey, " + person.persons_name 

private doesn't seem work if defining method on explicit object (in case self). can use private_class_method define class methods private (or described).

class person   def self.get_name     persons_name   end    def self.persons_name     "sam"   end    private_class_method :persons_name end  puts "hey, " + person.get_name puts "hey, " + person.persons_name 

alternatively (in ruby 2.1+), since method definition returns symbol of method name, can use follows:

class person   def self.get_name     persons_name   end    private_class_method def self.persons_name     "sam"   end end  puts "hey, " + person.get_name puts "hey, " + person.persons_name 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -