Skip to content

Instantly share code, notes, and snippets.

@joseph-ravenwolfe
Last active August 2, 2016 17:49
Show Gist options
  • Save joseph-ravenwolfe/59eb6e26db0256b2d73fbdf51f941bf1 to your computer and use it in GitHub Desktop.
Save joseph-ravenwolfe/59eb6e26db0256b2d73fbdf51f941bf1 to your computer and use it in GitHub Desktop.
Protected
# A good use case would be allowing an object to compare itself to another instance
class Country
attrs :name, :coordinates
def overlapping?(other)
self.coordinates_as_array.include?(other.coordinates_as_array)
end
protected
def coordinates_as_array
[x_coord, y_coord]
end
end
usa = Country.new('USA', 31.123, 28.678)
canada = Country.new('Canada', 29.321, 17.456)
# USA is allowed to call protected method 'coordinates_as_array' on Canada.
usa.overlapping?(canada) #=> false
# The following usage demonstrates that `private` does not limit methods
# to subclasses any more than protected does.
#
class TestClass
protected
def a_protected_method
puts "Superclass Protected Method"
end
private
def a_private_method
puts "Superclass Private Method"
end
end
class TestSubclass < TestClass
def call_protected_method_on_superclass
a_protected_method
end
def call_private_method_on_superclass
a_private_method
end
end
TestSubclass.new.call_protected_method_on_superclass
# The following call is expected to raise an exception, but doesn't
TestSubclass.new.call_private_method_on_superclass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment