Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 20th, 2012  |  syntax: None  |  size: 0.31 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class HashWithDefaults < Hash
  2.   def initialize(*args)
  3.     super(*args) { |_, key| self.defaults[key] }
  4.   end
  5.  
  6.   def defaults
  7.     @defaults ||= {}
  8.   end
  9. end
  10.  
  11. # Usage:
  12.  
  13. hash = HashWithDefaults.new
  14. p hash[:foo]  # => nil
  15. hash.defaults[:foo] = "foo"
  16. p hash[:foo]  # => "foo"
  17. hash[:foo] = "FOO"
  18. p hash[:foo]  # => "FOO"