Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created October 17, 2022 23:29
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 JoshCheek/ee8895c39c65378c9d3acc6a7b3f099b to your computer and use it in GitHub Desktop.
Save JoshCheek/ee8895c39c65378c9d3acc6a7b3f099b to your computer and use it in GitHub Desktop.
Alternate initialize for a hash, which is hopefully generally more user friendly
class Hash2 < Hash
def initialize(default_value=(use_proc=true; nil), &default_proc)
use_value = !use_proc
if use_value && default_proc
raise ArgumentError, "Provide a default value or a default proc, not both"
end
if use_value && !default_value.frozen?
raise ArgumentError, "Default values must be frozen"
end
default_proc ||= proc { default_value }
super() { |hash, key| hash[key] = default_proc[hash, key] }
end
end
Hash2.new # => {}
Hash2.new(0) { } rescue $! # => #<ArgumentError: Provide a default value or a default proc, not both>
Hash2.new([]) rescue $! # => #<ArgumentError: Default values must be frozen>
h = Hash2.new 0
h[:score] # => 0
h # => {:score=>0}
h = Hash2.new { [] }
h[:files] << "f1"
h[:dirs] << "d1"
h # => {:files=>["f1"], :dirs=>["d1"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment