根据另一个哈希中的值替换哈希值

时间:2012-11-19 16:05:43

标签: ruby hash

给定两个哈希值,我正在尝试替换第一个哈希值中的第二个哈希值所具有的键。具体来说,我有这两个哈希:

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] }]

但这并不是很有效。有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:4)

你可以这样做

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

答案 1 :(得分:2)

它被称为merge

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

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