class Person
def initialize(age)
@age = age
end
def is_how_many_younger_than(other_person)
age - other_person.age
end
protected # can't be 'private'
def age
@age
end
end
p1 = Person.new(10)
p2 = Person.new(15)
puts p1.is_how_many_younger_than p2
# => 5
The protected 'age' method is hidden yet accessible from another instance of the same class.
class Animal
def greet
hello
end
private
def hello
'Hello!'
end
end
class Cat < Animal
private
def hello # This overrides the parent's private hello method
'Meow!'
end
end
puts Animal.new.greet
# => Hello!
puts Cat.new.greet
# => Meow!
class Animal
private
def hello
# Private methods can be called from subclasses
'Hello!'
end
end
class Cat < Animal
def greet
hello
end
end
puts Cat.new.greet
# => Hello!