Created
November 25, 2013 12:58
-
-
Save stephanschubert/7640851 to your computer and use it in GitHub Desktop.
Hash#multi_fetch - Fetch multiple keys from a Hash and support default values when a key is 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
# Usage: | |
# | |
# h = { a: 1, b: 2 } | |
# | |
# h.multi_fetch(:a) # => [1] | |
# h.multi_fetch(:a, :b) # => [1, 2] | |
# h.multi_fetch(:a, :c) # => [1, nil] | |
# h.multi_fetch(a: 1, c: 3) # => [1, 3] | |
class Hash | |
def multi_fetch(*many) | |
if many.size == 1 and (defaults = many.first).is_a?(Hash) | |
reverse_merge(defaults).values_at(*defaults.keys) | |
else | |
values_at(*many) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment