Created
October 17, 2022 23:29
-
-
Save JoshCheek/ee8895c39c65378c9d3acc6a7b3f099b to your computer and use it in GitHub Desktop.
Alternate initialize for a hash, which is hopefully generally more user friendly
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
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