Created
September 8, 2017 18:31
-
-
Save JAMSUPREME/041553a3576a8b2dd5aa8cc860747545 to your computer and use it in GitHub Desktop.
Ruby private vs protected
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
class Hat | |
def explain | |
puts "You have a #{hat_type} hat!" | |
end | |
private | |
def hat_type | |
raise 'Child must implement hat type' | |
end | |
def default_hat_type | |
"Default" | |
end | |
protected | |
def secret_hat | |
"default secret" | |
end | |
end | |
class BigHat < Hat | |
def hat_type | |
"BIG" | |
end | |
end | |
class SmallHat < Hat | |
def explain | |
puts "You have a #{default_hat_type} hat!" | |
end | |
def secret_hat(other_hat) | |
puts "Secret hat is #{other_hat.secret_hat}" | |
end | |
end | |
class NotHat | |
def can_see_hat?(hat) | |
puts "Hat secret: #{hat.secret_hat}" | |
end | |
end | |
h = SmallHat.new | |
h_big = BigHat.new | |
no_hat = NotHat.new | |
h.secret_hat(h_big) | |
no_hat.can_see_hat?(h_big) # breaks, no_hat is not a hat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment