Last Updated: October 05, 2016
· codezombie

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) }

2 Responses
Add your response

IOU Beer. Thanks for posting.

over 1 year ago ·

If you are using Ruby on Rails or the Facets gem, you can use slice:


If not, I'd recommend select over reject, for a small readability improvement:

new_hash = { |key, _| keys.include?(key.to_s) }
over 1 year ago ·