给定两个哈希值,我正在尝试替换第一个哈希值中的第二个哈希值所具有的键。具体来说,我有这两个哈希:
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] }]
但这并不是很有效。有人能指出我正确的方向吗?
答案 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"}