首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ruby选择元素嵌套哈希相同的键

ruby选择元素嵌套哈希相同的键
EN

Stack Overflow用户
提问于 2014-07-04 03:05:36
回答 1查看 1.1K关注 0票数 0

下面有一个散列,我试图从中获得元素的“值”,该元素匹配‘’=>‘2014年’和‘=>’M06‘’。

代码语言:javascript
复制
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"=>[{}]}]}]}}

到目前为止,我得到了“结果”,其结果是:

代码语言:javascript
复制
{"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,选择该元素,然后从元素中获得值。我该怎么做?

我意识到,从技术上讲,我可以采取第一个嵌套的哈希,因为我正在寻找最高时期,但这似乎草率。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-04 03:27:56

你可以

代码语言:javascript
复制
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方法。

举例说明:-

代码语言:javascript
复制
#!/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) # => 11
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24566126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档