Created
January 18, 2012 18:29
-
-
Save epitron/1634677 to your computer and use it in GitHub Desktop.
Hash with set operations
This file contains hidden or 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
| # | |
| # The original idea was to use set operations to help dealing with a method's "options" hash. | |
| # | |
| # However, since I can't override || and &&, I wasn't able to figure out reasonable semantics. | |
| # | |
| # Therefore, I implemented `with_defaults`, which is what you want most of the time, and then | |
| # wrote some thoughts about how set operations might work. | |
| # | |
| class Hash | |
| # | |
| # Fills in defaults that don't exist, and removes keys that aren't allowed. | |
| # | |
| # Example: | |
| # | |
| # options = { | |
| # :opt1 => "Hey!", | |
| # :opt2 => "what", | |
| # :opt3 => nil, # explicitly defined nils override defaults. | |
| # :badopt => 6666 # this will be exluded, since it's not defined in the defaults. | |
| # } | |
| # | |
| # p options.with_defaults( | |
| # :opt1 => nil, | |
| # :opt2 => "Amazing.", | |
| # :opt3 => 3.14159265358979323846264338327950, | |
| # :opt4 => 42 | |
| # ) | |
| # | |
| # Output: | |
| # | |
| # {:opt1=>"Hey!", :opt2=>"what", :opt3=>nil, :opt4=>42} | |
| # | |
| def with_defaults(defaults) | |
| valid = defaults.keys | |
| supplied = keys & valid | |
| result = defaults.dup | |
| supplied.each do |k| | |
| result[k] = self[k] | |
| end | |
| result | |
| end | |
| def +(other) | |
| # merge the two hashes (and union their sets of values) | |
| end | |
| def -(other) | |
| # subtract the hashes (and subtract their sets of values) | |
| end | |
| def &(other) | |
| # intersect the hashes (include key/value pairs that are identical) | |
| end | |
| def |(other) | |
| # overlay "other" onto self (replacing self's values with other's) | |
| end | |
| def ^(other) | |
| # find keys that are unique to each hash | |
| end | |
| end | |
| options = { | |
| :opt1 => "Hey!", | |
| :opt2 => "what", | |
| :opt3 => nil, # explicitly defined nils override defaults. | |
| :badopt => 6666 # this will be exluded, since it's not defined in the defaults. | |
| } | |
| p options.with_defaults( | |
| :opt1 => nil, | |
| :opt2 => "Amazing.", | |
| :opt3 => 3.14159265358979323846264338327950, | |
| :opt4 => 42 | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment