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
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"