Reputation: 421
I have a hash of an array of arrays. The array is indexed by the hash (that is the way I am reading this):
[
{"name":"G18","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]},
{"name":"G19","data": [["M16",141],["M203",57],["M29S",142]]},
{"name":"G20","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]}
]
I want to select the hashes that contain the array G18
, and return only the data.
I tried searching for answer, but I haven't found anything like this yet.
Upvotes: 1
Views: 97
Reputation: 6564
This will work for you if you have only one item with name "G18":
a.find {|e| e[:name] == "G18" }[:data]
See: Enumerable#find in the official docs.
Upvotes: 3
Reputation: 786
collection = [
{"name":"G18","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]},
{"name":"G19","data": [["M16",141],["M203",57],["M29S",142]]},
{"name":"G20","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]}
]
def data_for_name(name, collection)
collection.find { |item| item[:name] == name }[:data]
end
p data_for_name("G18", collection)
Upvotes: 2
Reputation: 20263
Given:
ary = [
{"name":"G18","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]},
{"name":"G19","data": [["M16",141],["M203",57],["M29S",142]]},
{"name":"G20","data": [["X301",141],["x7901",57],["x2100",142],["x90",58]]}
]
Try:
ary.select{|hsh| hsh[:name] == 'G18'}.first[:data]
=> [["X301", 141], ["x7901", 57], ["x2100", 142], ["x90", 58]]
In fact, marmeladze's answer is the correct one:
ary.find{|hsh| hsh[:name] == 'G18'}[:data]
Using select
was a misfire.
Upvotes: 3