What are the differences between “private”, “public”, and “protected methods”?

后端 未结 7 1632
栀梦
栀梦 2020-12-08 04:03

I\'m learning Ruby, and have come up to a point where I am confused.

The book I am using is talking about private, public, and protec

相关标签:
7条回答
  • 2020-12-08 05:00

    I think breaking down an explicit receiver is what is important if your having trouble grasping the concept.

    An explicit receiver is an object that is accepting a message.

     person.get_name
    

    person is the receiver and the method "get_name" is giving instructions to the object "person" to perform the method "get_name".

    class Person
        attr_accessor :first_name, :last_name 
    
      def initialize(first_name, last_name)
        @first_name = first_name
        @last_name = last_name
        puts "And #{phone_number}" # Private method called when initialized
      end
    
      private 
      def phone_number
        return "XXX-XXX-XXXX"
      end
    end
    
    
    p p1 = Person.new("mike", "jones")
    
    
    p p1.phone_number # Not within the context of the object instance.
    

    When a method is private, it can only be used by other methods inside the object in whose class it is defined.

    0 讨论(0)
提交回复
热议问题