Skip to content

Instantly share code, notes, and snippets.

@Peeja
Created July 2, 2013 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Peeja/5906069 to your computer and use it in GitHub Desktop.
Save Peeja/5906069 to your computer and use it in GitHub Desktop.
A new use for Ruby's `protected`.
# 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