Skip to content

Instantly share code, notes, and snippets.

@softcraft-development
Created June 13, 2010 23:45
Show Gist options
  • Save softcraft-development/437101 to your computer and use it in GitHub Desktop.
Save softcraft-development/437101 to your computer and use it in GitHub Desktop.
Retrieve a value from a Hash. If the key is not in the hash, return the given default value and save it to the hash
class Hash
# Pass either a default value or a block to return it (a la Hash#fetch()).
# If both are passed, the block will take precedence over the default value
def evoke(key, default = nil)
if include?(key)
self[key]
else
self[key] = block_given? ? yield : default
end
end
end
class TestHashExtensions < Test::Unit::TestCase
def test_evoke_found_block
hash = {:test => "test"}
assert_equal "test", hash.evoke(:test) {"not test"}
end
def test_evoke_found_default
hash = {:test => "test"}
assert_equal "test", hash.evoke(:test, "not test")
end
def test_evoke_returns_default
hash = {}
assert_equal "not test", hash.evoke(:test, "not test")
end
def test_evoke_returns_block
hash = {}
assert_equal "test", hash.evoke(:test) {"test"}
end
def test_evoke_found_default_does_not_add
hash = {:test => "test"}
hash.evoke(:test, "not test")
assert_equal "test", hash[:test]
end
def test_evoke_found_block_does_not_add
hash = {:test => "test"}
hash.evoke(:test) {"not test"}
assert_equal "test", hash[:test]
end
def test_evoke_default_adds
hash = {}
hash.evoke(:test, "test")
assert_equal "test", hash[:test]
end
def test_evoke_block_adds
hash = {}
hash.evoke(:test) { "test" }
assert_equal "test", hash[:test]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment