Skip to content

Instantly share code, notes, and snippets.

@dyanagi
Last active April 5, 2019 19:16
Show Gist options
  • Save dyanagi/d627f139bd8199618bc714d9f68d593c to your computer and use it in GitHub Desktop.
Save dyanagi/d627f139bd8199618bc714d9f68d593c to your computer and use it in GitHub Desktop.
Examples in using "protected" and "private" in Ruby

Protected Methods in Ruby

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.

Private Methods in Ruby

Subclasses can override superclasses

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!

Private methods can be called from subclasses

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!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment