Is there an elegant way in Ruby to filter a hash of arrays of hashses?

408 views Asked by At

Let's say I have a this type of data structure:

{
  "foo": [{state: on}, {state: off}, {state: on}],
  "bar": [{state: off}, {state: off}, {state: on}],
  "baz": [{state: on}, {state: on}, {state: on}]
}

How can I filter the nested hash arrays in an elegant way so I can get back this:

{
  "foo": [{state: on}, {state: on}],
  "bar": [{state: on}],
  "baz": [{state: on}, {state: on}, {state: on}]
}
2

There are 2 answers

0
Rajagopalan On BEST ANSWER
a={
    "foo": [{state: "on"}, {state: "off"}, {state: "on"}],
    "bar": [{state: "off"}, {state: "off"}, {state: "on"}],
    "baz": [{state: "on"}, {state: "on"}, {state: "on"}]
}

Code

p a.transform_values{|arr| arr.select{|h|h[:state].eql?'on'}}

Result

{:foo=>[{:state=>"on"}, {:state=>"on"}], :bar=>[{:state=>"on"}], :baz=>[{:state=>"on"}, {:state=>"on"}, {:state=>"on"}]}
2
max On

Given:

data = {
  "foo": [{state: :on}, {state: :off}, {state: :on}],
  "bar": [{state: :off}, {state: :off}, {state: :on}],
  "baz": [{state: :on}, {state: :on}, {state: :on}]
}

Use #transform_values to iterate and replace the hash values and #select to filter the elements in the array:

data.transform_values do |value|
  value.select { |hash| hash[:state] == :on  }
end