Created
July 6, 2012 00:05
-
-
Save roryokane/3057238 to your computer and use it in GitHub Desktop.
Ruby Hash monkey-patch methods relating to the hash’s default
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
# encoding: utf-8 | |
class Hash | |
def with_new_default(*hash_new_args, &hash_new_block) | |
empty_defaulting_hash = Hash.new(*hash_new_args, &hash_new_block) | |
# using #merge; #replace would also replace the default value | |
return empty_defaulting_hash.merge(self) | |
end | |
def with_default(*args, &block) | |
# like with_new_default, but requires an argument – | |
# it wouldn’t make sense to write `{a: 1}.with_default` | |
# TODO implement | |
end | |
end |
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
{a: 1, b: 2}.with_default(:missing) | |
{a: 1, b: 2}.with_default{Time.now} | |
my_hash_with_a_bad_default.with_default(:missing) | |
my_hash_with_a_bad_default.with_default{Time.now} | |
my_hash_with_a_bad_default.with_new_default | |
my_hash_with_a_bad_default.with_new_default(:missing) | |
my_hash_with_a_bad_default.with_new_default{Time.now} |
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
# encoding: utf-8 | |
class Hash | |
# These methods supplement Hash#default and #default_proc when exploring unfamiliar hashes. | |
def default_is_proc? | |
! default_proc.nil? | |
# Checking #default wouldn’t help; it could be anything. | |
# But #default_proc is either a Proc or nil. | |
end | |
def default_type | |
if default_is_proc? | |
:proc | |
else | |
:value | |
end | |
end | |
end |
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 Hash | |
def use_default_default! | |
default_hash = {} | |
if default_hash.default_is_proc? | |
self.default_proc = default_hash.default_proc | |
else | |
self.default = default_hash.default | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment