Extract key/value pairs from a hash in ruby using an array of keys.
I recently needed to extract a hash of key/value pairs from an existing hash in ruby, using an array of keys. This is pretty straight forward, and can be done in a single line.
# The keys you're looking for
keys = %w(key1 key2 key3)
# Hash with any number of key / value pairs
original_hash = {
key1: 'Value 1',
key2: 'Value 2',
key3: 'Value 3',
key4: 'Value 4'
}
# New hash, with only the keys you specified.
new_hash = original_hash.reject { |x| !keys.include?(x.to_s) }
Written by Mike Kelley
Related protips
2 Responses
IOU Beer. Thanks for posting.
over 1 year ago
·
If you are using Ruby on Rails or the Facets gem, you can use slice:
original_hash.slice(*keys)
If not, I'd recommend select
over reject
, for a small readability improvement:
new_hash = original_hash.select { |key, _| keys.include?(key.to_s) }
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#