Last active
August 29, 2015 14:22
-
-
Save mwlang/6aee66cceae52ef03979 to your computer and use it in GitHub Desktop.
Simple deep-dive hash access when it's likely a key may be missing.
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
"Foo Bar!" | |
nil | |
nil | |
nil | |
"One" | |
"****************************************" | |
"Foo Bar!" | |
"boom" | |
"boom" | |
"boom" | |
"One" |
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
foo = { | |
fe: "One", | |
fo: "Foe", | |
bar: { | |
baz: { | |
foobar: "Foo Bar!" | |
} | |
} | |
} | |
module SafeHashValues | |
def value_at *keys | |
keys.reduce(self) do |m, k| | |
if m.respond_to?(:fetch) | |
m.fetch(k) { yield if block_given? } | |
else | |
yield if block_given? | |
end | |
end | |
end | |
end | |
def log value | |
puts value.inspect | |
end | |
foo.extend(SafeHashValues) | |
log foo.value_at(:bar, :baz, :foobar) | |
log foo.value_at(:bar, :baz, :foobar, :bang) | |
log foo.value_at(:bar, :baz, :foobar, :bang) | |
log foo.value_at :bar, :bat, :foobar | |
log foo.value_at :fe | |
log '*' * 40 | |
log foo.value_at(:bar, :baz, :foobar) { "boom" } | |
log foo.value_at(:bar, :baz, :foobar, :bang) { "boom" } | |
log foo.value_at(:bar, :baz, :foobar, :bang) { "boom" } | |
log foo.value_at(:bar, :bat, :foobar) { "boom" } | |
log foo.value_at(:fe) { "boom" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment