Muhammad Umer Muhammad Umer - 4 months ago 7
Ruby Question

is there a built in way to get new hash consisting of only certain key in Ruby?

Say i have data hash like this:

data = [{..}, {..}, {..}]


each hash is like this

{ :ctiy => 'sdfd', :pop => 33, :best_food=> 'sdfa'....}


now how can I get an Array of hashes only containing certain key/value or multiple keys. So take city, if I want new array of hashes containing city only.

I know, I can loop and filter manually but is there a built in method I am missing on.

Answer

map will help:

original_array_of_hashes.map do |hash|
  { city: hash[:city] }
end

If you're using Rails, the slice method will be available:

original_array_of_hashes.map do |hash|
  hash.slice(:city)
end

For multiple keys:

# without 'slice'
original_array_of_hashes.map do |hash|
  { key_one: hash[:key_one], key_two: hash[:key_two] }
end

# with 'slice'    
original_array_of_hashes.map do |hash|
  hash.slice(:key_one, :key_two)
end