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

后端 未结 7 1767
栀梦
栀梦 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 04:40

    Studying the information I've taken from here, I extended explanations through errors, and for my opinion, helps to understand why and how to use protected and not private.

    1) Protected:

    The line num 12 crash because the parameter received is from another class, the error message is clear:

    v.rb:12:in `==': undefined method `sku' for "Object of another class ==> crash":String (NoMethodError)
    

    2) Private:

    If remove self from line 8 and 12, and I change protected for private, crash because in line 12, other doesn't know what sku is:

    v.rb:12:in `==': private method `sku' called for # (NoMethodError)
    

    The program:

    class Product
      attr_accessor :name, :quantity
    
      def initialize(name)
        @name = name
        @quantity = 1
    
        puts "The SKU is #{self.sku}"
      end
    
      def == (other)
        self.sku == other.sku
      end
    
      protected
        def sku
          name.crypt("yo")
        end
    end
    
    milk1 = Product.new("Milk")
    milk2 = Product.new("Milk")
    bread = Product.new("Bread")
    
    puts milk1 == bread
    
    puts milk1 == milk2
    
    puts milk1 == "Object of another class ==> crash"
    

提交回复
热议问题