3

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

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

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

4

3 回答 3

4

你可以这样做

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

于 2012-11-19T16:09:42.367 回答
2

它称为合并

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

data.merge(conditions)
#{"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
于 2012-11-19T16:16:46.617 回答
2

方法 merge 可以占用一个块,您可以在其中进行一些特定操作,而不仅仅是分配新值

data.merge(conditions) do |key, oldvalue, newvalue|
  newvalue
end    
=> {"study"=>"((current))", "name"=>"Lucid Plan", "studyWillBe"=>"Combination"}
于 2012-11-19T18:40:03.810 回答