下面有一个散列,我试图从中获得元素的“值”,该元素匹配‘’=>‘2014年’和‘=>’M06‘’。
result = {"status"=>"REQUEST_SUCCEEDED", "responseTime"=>28, "message"=>[], "Results"=>{"series"=>[{"seriesID"=>"LNU03034342", "data"=>[{"year"=>"2014", "period"=>"M06", "periodName"=>"June", "value"=>"11.1", "footnotes"=>[{}]}, {"year"=>"2014", "period"=>"M05", "periodName"=>"May", "value"=>"16.8", "footnotes"=>[{}]}, {"year"=>"2014", "period"=>"M04", "periodName"=>"April", "value"=>"18.8", "footnotes"=>[{}]}, {"year"=>"2014", "period"=>"M03", "periodName"=>"March", "value"=>"18.7", "footnotes"=>[{}]}, {"year"=>"2014", "period"=>"M02", "periodName"=>"February", "value"=>"17.6", "footnotes"=>[{}]}, {"year"=>"2014", "period"=>"M01", "periodName"=>"January", "value"=>"16.0", "footnotes"=>[{}]}]}]}}到目前为止,我得到了“结果”,其结果是:
{"year"=>"2014", "period"=>"M06", "periodName"=>"June", "value"=>"11.1", "footnotes"=>[{}]}
{"year"=>"2014", "period"=>"M05", "periodName"=>"May", "value"=>"16.8", "footnotes"=>[{}]}
{"year"=>"2014", "period"=>"M04", "periodName"=>"April", "value"=>"18.8", "footnotes"=>[{}]}
{"year"=>"2014", "period"=>"M03", "periodName"=>"March", "value"=>"18.7", "footnotes"=>[{}]}
{"year"=>"2014", "period"=>"M02", "periodName"=>"February", "value"=>"17.6", "footnotes"=>[{}]}
{"year"=>"2014", "period"=>"M01", "periodName"=>"January", "value"=>"16.0", "footnotes"=>[{}]}现在,这个父散列的每个元素中的所有键都是相同的,所以我需要通过搜索M06,选择该元素,然后从元素中获得值。我该怎么做?
我意识到,从技术上讲,我可以采取第一个嵌套的哈希,因为我正在寻找最高时期,但这似乎草率。
发布于 2014-07-04 03:27:56
你可以
result["Results"]["series"][0]["data"].find(->(){ {} }) do |hash|
hash[period] == 'M06'
end.fetch(value, "period not found")
#find-将每个条目以枚举形式传递到块中。返回第一个不为false的块。如果没有匹配的对象,则调用ifnone并在指定时返回其结果,否则返回nil。
因此,由于任何原因,如果在任何散列中找不到键周期的'M06'值,则#find将调用我传递给它的参数,如->() { {} }.call,并返回空哈希,否则如果'M06'找到任何散列的键'period,则将返回该哈希。在这个返回的散列上,我调用Hash#fetch方法。
举例说明:-
#!/usr/bin/env ruby
array = {a: 1, b: 2}, { a: 4, b: 11}
def fetch_value(array, search_key, search_value, fetch_key)
array.find(->(){ {} }) do |h|
h[search_key] == search_value
end.fetch(fetch_key, "#{search_value} is not found for #{search_key}.")
end
fetch_value(array, :a, 11, :b) # => "11 is not found for a."
fetch_value(array, :a, 4, :b) # => 11https://stackoverflow.com/questions/24566126
复制相似问题