Muhammad Umer Muhammad Umer - 1 year ago 46
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 Source

map will help: do |hash|
  { city: hash[:city] }

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

For multiple keys:

# without 'slice' do |hash|
  { key_one: hash[:key_one], key_two: hash[:key_two] }

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