Created
July 2, 2013 01:12
-
-
Save Peeja/5906069 to your computer and use it in GitHub Desktop.
A new use for Ruby's `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
# Say you're implementing a hash map, and you've got two | |
# sets of algorithms which are more efficient at | |
# different sizes: | |
class HashMap | |
class << self | |
def with_values(values) | |
if values.size > 64 | |
LargeHashMap.new(values) | |
else | |
SmallHashMap.new(values) | |
end | |
end | |
protected :new | |
end | |
class LargeHashMap < self | |
# Efficient algorithms for large hash maps | |
end | |
class SmallHashMap < self | |
# Efficient algorithms for small hash maps | |
end | |
end | |
# If .new were private, the superclass's .with_values | |
# couldn't call it. Since it's protected, other objects | |
# can't call HashMap.new (or LargeHashMap.new). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment