【问题标题】:Selecting items from a Ruby Hash从 Ruby 哈希中选择项目
【发布时间】:2013-03-09 02:09:43
【问题描述】:

我在 Ruby 中有一个如下所示的哈希:

{"NameValues"=>[
    {"Name"=>"Field 1", "Values"=>["Data 1"]}, 
    {"Name"=>"Field 2", "Values"=>["Data 2"]}, 
    {"Name"=>"Field 3", "Values"=>["Data 3"]}, 
    {"Name"=>"Field 4", "Values"=>["Data 4"]}, 
    {"Name"=>"Field 5", "Values"=>["Data 5"]}
]}

我想通过使用“Names”元素中的名称来选择“Values”元素的内容,例如,通过搜索“Field 3”等找到“Data 3”字符串。

【问题讨论】:

  • 您可能希望查看重构生成哈希的代码。哈希不是很有用,因为它迫使您跳过箍,并且应该/可以简化为每个“名称”值实际上是指向“值”值的键。
  • 是的,我同意 - 不幸的是,这超出了我的控制范围。

标签: ruby hash


【解决方案1】:

您可以使用Enumerable#find 方法按名称查找哈希:

hash = {"NameValues"=>[
    {"Name"=>"Field 1", "Values"=>["Data 1"]}, 
    {"Name"=>"Field 2", "Values"=>["Data 2"]}, 
    {"Name"=>"Field 3", "Values"=>["Data 3"]}, 
    {"Name"=>"Field 4", "Values"=>["Data 4"]}, 
    {"Name"=>"Field 5", "Values"=>["Data 5"]}
]}

p hash['NameValues'].find{ |h| h['Name'] == 'Field 3'}['Values']
#=> ["Data 3"]

find 基本上遍历NameValues 数组,直到找到匹配的元素。然后,您可以从返回的元素中获取Values

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 2021-12-17
    • 2012-01-30
    • 2016-11-02
    • 1970-01-01
    • 2017-01-16
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多