【问题标题】:Ruby - Elegantly replace hash values with nested value (description)Ruby - 用嵌套值优雅地替换哈希值(描述)
【发布时间】:2016-06-10 16:37:23
【问题描述】:

我正在使用的哈希值有一个哈希值,它总是包含一个 ID、名称和描述。我对保留 ID 或名称不感兴趣,只想用相应的描述替换每个哈希值。

代码

hsh['nested']['entries']['addr'] = hsh['nested']['entries']['addr']['description']
hsh['nested']['entries']['port'] = hsh['nested']['entries']['port']['description']
hsh['nested']['entries']['protocol'] = hsh['nested']['entries']['protocol']['description']
hsh['nested']['entries']['type'] = hsh['nested']['entries']['type']['description']
... (many more)

这很好用,但不是很优雅——实际上,我有 20 个条目/行代码来完成这项工作。

哈希值的结构(对于hsh['nested']['entries']['addr']

{ "id" => "27", "name" => "Instance", "description" => "**This is what I need.**" }

以上面第一行代码为例,最终结果是hsh['nested']['entries']['addr']的值变成**This is what I need.**

实现这一目标的优雅方法是什么?

【问题讨论】:

  • 请调整您的示例代码和数据,使其可运行,并演示您遇到的问题。 “minimal reproducible example”描述了如何提问。我们需要演示问题的最少代码,以及最少的输入数据和您的预期输出。虽然我们可以拼凑数据,但它迫使我们使用不同的起点,这会导致不准确和混淆答案的可能性。请记住,您的问题和我们的答案是一篇文章,旨在帮助未来的搜索者找到类似的解决方案,而不仅仅是为您解答。
  • 抱歉,如果可能的话,我会在星期一审查并更正此问题。谢谢。

标签: ruby


【解决方案1】:
hsh = { 'nested'=>
        { 'entries'=>
          { 
            'addr'=>{ "id" => "1", "description"=>"addr" },
            'port'=>{ "id" => "2", "description"=>"port" },
            'cats'=>{ "id" => "3", "description"=>"dogs" },
            'type'=>{ "id" => "4", "description"=>"type" }
          }
        }
      }

keys_to_replace = ["addr", "port", "type"]

hsh['nested']['entries'].tap { |h| keys_to_replace.each { |k| h[k]=h[k]["description"] }
  #=> { "addr"=>"addr",
  #     "port"=>"port",
  #     "cats"=>{"id"=>"3", "description"=>"dogs"},
  #     "type"=>"type"
  #   } 

hsh
  #=> {"nested"=>
  #     { "entries"=>
  #       { "addr"=>"addr",
  #         "port"=>"port",
  #         "cats"=>{"id"=>"3", "description"=>"dogs"},
  #         "type"=>"type"
  #       }
  #     } 
  #   }

【讨论】:

  • 以前从未使用过tap,我会尽快回顾一下它的工作原理,看看哪个答案最可靠。欣赏它。
  • 您会发现它们同样强大。主要区别在于tap 返回修改后的hsh,而@seph 的答案没有。如果嵌入到方法中,seph 必须添加 hsh 作为最后一行。这种差异很小。我认为这取决于个人喜好,也许哪种方法“阅读”最好。
  • 我会把这个给@seph,只是因为给了失败者一些分数。显然,您不需要更多:)。即便如此,这是一个非常有用的解释,我理解其中的区别。将来当我需要返回相同的更改哈希时,我可能会使用您的代码。在这种情况下,我不需要担心重建哈希。所以要明确一点,如果我在方法中使用 seph 的答案,我需要返回哈希值——知道了。
  • 赞成,因为您提供的代码在某些情况下绝对有用。 @seph's 是最干净的阅读,我正在为需要进来并理解的未来用户编写代码——他们可能没有那么多 Ruby 背景。像往常一样感谢卡里。我最不喜欢的部分是在 2 个正确答案之间进行选择。
【解决方案2】:
sub_hash = hsh['nested']['entries']
categories = %w{addr port protocol type}

categories.each do |category|
  sub_hash[category] = sub_hash[category]['description']
end

【讨论】:

  • 谢谢,我会在星期一测试并报告。
猜你喜欢
  • 2012-05-08
  • 2013-07-21
  • 1970-01-01
  • 2014-09-15
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
相关资源
最近更新 更多