Skip to content

Instantly share code, notes, and snippets.

@JAMSUPREME
Created September 8, 2017 18:31
Show Gist options
  • Save JAMSUPREME/041553a3576a8b2dd5aa8cc860747545 to your computer and use it in GitHub Desktop.
Save JAMSUPREME/041553a3576a8b2dd5aa8cc860747545 to your computer and use it in GitHub Desktop.
Ruby private vs protected
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