Last active
July 12, 2024 01:21
-
-
Save gohkhoonhiang/fb5b4b45e44326c21bd025b19538df07 to your computer and use it in GitHub Desktop.
A reminder of how ruby's access scope works in inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
###### | |
## A reminder of how ruby's access scope works in inheritance | |
## public: can be called by ownself, any other class | |
## protected: can be called by ownself, sibling class | |
## private: can be called by ownself | |
###### | |
class Animal | |
attr_reader :breed | |
def initialize(breed) | |
@breed = breed | |
end | |
def speak | |
p "#{breed} public speak" | |
end | |
protected | |
def habit | |
p "#{breed} protected habit" | |
end | |
private | |
def behave | |
p "#{breed} private behave" | |
end | |
end | |
class Dog < Animal | |
def speak | |
p "Woof!" | |
habit | |
behave | |
cat = Cat.new("orange") | |
cat.habit | |
#cat.behave | |
end | |
end | |
class Cat < Animal | |
def speak | |
p "Meow!" | |
habit | |
behave | |
dog = Dog.new("husky") | |
dog.habit | |
#dog.behave | |
end | |
end | |
corgi = Dog.new("corgi") | |
persian = Cat.new("persian") | |
corgi.speak | |
persian.speak | |
######### | |
# [2] pry(main)> load 'test_oop.rb' | |
# "Woof!" | |
# "corgi protected habit" | |
# "corgi private behave" | |
# "orange protected habit" | |
# "Meow!" | |
# "persian protected habit" | |
# "persian private behave" | |
# "husky protected habit" | |
# => true | |
# | |
# If we try to call the .behave private method of sibling class: | |
# | |
# NoMethodError: private method `behave' called for #<Cat:0x0000000107baa6a0 @breed="orange"> | |
# from test_oop.rb:32:in `speak' | |
# | |
# We also can't call the .habit protected method from outside of the class: | |
# | |
corgi.habit | |
# NoMethodError: protected method `habit' called for #<Dog:0x0000000164a2e378 @breed="corgi"> | |
# from test_oop.rb:51:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment