【问题标题】:ruby select element nested hash same keysruby 选择元素嵌套哈希相同的键
【发布时间】:2014-07-04 12:53:41
【问题描述】:

我有下面的哈希,我试图从中获取匹配“年份”=>“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"=>[{}]}]}]}}

到目前为止,我有 'result["Results"]["series"][0]["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"=>[{}]}

现在,这个父哈希的每个元素中的所有键都是相同的,所以我需要通过搜索 M06 的周期来获得我想要的,选择那个元素,然后从元素中获取值。我该怎么做呢?

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

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    你可以这样做

    result["Results"]["series"][0]["data"].find(->(){ {} }) do |hash|
        hash[period] == 'M06'
    end.fetch(value, "period not found")
    

    #find - 将枚举中的每个条目传递给阻塞。返回第一个不为假的块。 如果没有对象匹配,则调用 ifnone 并在指定时返回结果,否则返回 nil。

    因此,如果从任何 hash 中找不到键 period'M06' 值,则出于任何原因,#find 将调用 参数 我传递给它,比如->() { {} }.call,并返回空散列,否则如果'M06' 找到任何散列的键'period,那么散列 将被返回。在这个返回的 hash 上,我正在调用 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) # => 11
    

    【讨论】:

    • 我知道这行得通,谢谢。但是,我不太了解->(){ {} } 所做的事情。您介意详细说明吗?
    • @UserDuser 这是一个Proc 对象,我使用staby 运算符 创建它。这与lambda() { {} } 相同。现在清楚了吗? proc 对象包含一个 空散列 ({}),当您调用 proc 对象 时将返回该散列。
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多