Skip to content

Instantly share code, notes, and snippets.

@stephanschubert
Created November 25, 2013 12:58
Show Gist options
  • Save stephanschubert/7640851 to your computer and use it in GitHub Desktop.
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.
# 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