1

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}]
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Jarad DeLorenzo
  • 329
  • 2
  • 10

2 Answers2

4
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"}]}
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
0

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
max
  • 96,212
  • 14
  • 104
  • 165