sshdkg
Last Updated: October 05, 2016
·
4.823K
· codezombie
B9d5abee1482afbf6b987edd5e95e7b5

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) }
Say Thanks
Respond

2 Responses
Add your response

17478
None

IOU Beer. Thanks for posting.

over 1 year ago ·
28210

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 ·