【问题标题】:Replace hash value based on the value in another hash根据另一个哈希中的值替换哈希值
【发布时间】:2012-11-20 02:56:53
【问题描述】:

给定两个散列,我试图将第一个散列中的值替换为第二个散列也具有的键。具体来说,我有这两个哈希:

data = {
  "study"       => "Lucid Study",
  "name"        => "Lucid Plan",
  "studyWillBe" => "Combination"
}

conditions = { "study" => "((current))" }

我希望data 更新其"study" 密钥,因为conditions 拥有该密钥。我希望data 以这样的方式结束:

data = {
  "study"       => "((current))",
  "name"        => "Lucid Plan",
  "studyWillBe" => "Combination"
}

我已经走到这一步了:

data = Hash[data.map {|k, v| [conditions[k] || k, v] }]

但这并不完全奏效。谁能指出我正确的方向?

【问题讨论】:

    标签: ruby hash


    【解决方案1】:

    你可以这样做

    data.each {|k, v| data[k] = conditions[k] if conditions[k]}

    【讨论】:

    • 这是完美的,完全符合我的需要。非常感谢您的快速回复。
    【解决方案2】:

    它叫merge

    data = {"study"=>"Lucid Study", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
    conditions = {"study"=>"((current))"}
    
    data.merge(conditions)
    #{"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
    

    【讨论】:

    • conditions 有一个data 没有的键时,这将给出错误的结果。
    【解决方案3】:

    方法合并可以带一个块,你可以在其中进行一些特定的操作,而不仅仅是分配新值

    data.merge(conditions) do |key, oldvalue, newvalue|
      newvalue
    end    
    => {"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
    

    【讨论】:

      猜你喜欢
      • 2013-07-21
      • 1970-01-01
      • 2020-02-20
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2013-07-23
      相关资源
      最近更新 更多