RedOster
RedOster

Reputation: 325

Search array of dissimilar hashes

I have an array of hashes, each of which has non-normalized values like this:

arr = [{
    id: 0,
    type: 'character',
    person: {
      name: 'Steve Rogers',
      weapon: 'Shield',
      known: true
    }
  },
  {
    id: 1,
    type: 'organization',
    company: "Pym Industries",
    tech: 'Shrinking suit'
  },
  {
    id: 2,
    type: 'character',
    person: {
      name: 'Tony Stark',
      weapon: 'Ironman Suit',
      known: false
    }
  }]

Some of the hashes are different. I want to get a subarray of hashes whose person I know, i.e., arr.person.known is true. The result should be like:

subarr = [{
    id: 0,
    type: 'character',
    person: {
      name: 'Steve Rogers',
      weapon: 'Shield',
      known: true
    }
  }]

I tried:

b = arr.select{|x| x.person.known}
b = arr.reject{|x| if x.person then x.person.known}

But I bump into NoMethodError: undefined method `person' for Hash:0x007fc5f6f587f0.

Upvotes: 0

Views: 42

Answers (1)

Ursus
Ursus

Reputation: 30056

Try this one

arr.select { |item| item.fetch(:person, {})[:known] }

or

arr.select { |item| (item[:person] || {})[:known] }

or, from Ruby 2.3.0

arr.select { |item| item.dig(:person, :known) }

More verbose but maybe clearer

arr.select do |item|
  person = item.fetch(:person, {})
  person[:known]
end

or

arr.select { |item| item[:person] && item[:person][:known] }

Upvotes: 6

Related Questions