Search code examples
rubyfilterruby-hash

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


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

Solution

  • 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"}]}