0

I have the following json string:

[{"name": "John", "room": "A"},
 {"name": "Nick", "room": "A"},
 {"name": "Bill", "room": "B"}]

How can I extract the records whose "room" value equals "A" without iterating over all of them explicitly?

I'm looking for a simple way to search over elements.

Beetlejuice
  • 4,292
  • 10
  • 58
  • 84

1 Answers1

1

Use Array#select

> array.select{|a| a[:room] == "A"}
#=> [{:name=>"John", :room=>"A"}, {:name=>"Nick", :room=>"A"}]
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
  • 1
    I am not sure whether OP wanted to avoid this. – sawa Jul 23 '15 at 08:59
  • @sawa : Why? Is OP expected anything else – Gagan Gami Jul 23 '15 at 09:00
  • The OP wrote they wanted to avoid explicitly iterating over. It is not clear what that means, but your answer may be such case. – sawa Jul 23 '15 at 09:02
  • @sawa : yes you are right. Even I m also confused with that but I assume generally he want this only. If OP make clear so I can modify my answer as per his requirement. – Gagan Gami Jul 23 '15 at 09:03
  • 1
    So, since there's no explicit `.each` in the code above, this does qualify per OP's definition. While it does (internally) iterate through, doing otherwise is practically impossible :} – D-side Jul 23 '15 at 09:07
  • 1
    @D-side but it's **iterate** over an array. – Roman Kiselenko Jul 23 '15 at 09:09
  • @D-side : Is there any other best way then love to see as post. – Gagan Gami Jul 23 '15 at 09:11
  • 1
    @GaganGami I believe yours is *the one*. The array structure implies this can't be done more efficiently anyway. If that were something else, there would be room for thought. – D-side Jul 23 '15 at 09:12