如何在Ruby中复制散列? [英] How do I copy a hash in Ruby?
问题描述
我承认我是一个红宝石新手(现在写rake脚本)。在大多数语言中,复制构造函数很容易找到。半小时的搜索没有发现红宝石。我想创建一个散列的副本,以便我可以修改它而不影响原始实例。
I'll admit that I'm a bit of a ruby newbie (writing rake scripts, now). In most languages, copy constructors are easy to find. Half an hour of searching didn't find it in ruby. I want to create a copy of the hash so that I can modify it without affecting the original instance.
一些预期的方法无法按预期工作:
Some expected methods that don't work as intended:
h0 = { "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash
与此同时,我采取了这种不合理的解决方法
In the meantime, I've resorted to this inelegant workaround
def copyhash(inputhash)
h = Hash.new
inputhash.each do |pair|
h.store(pair[0], pair[1])
end
return h
end
推荐答案
The clone
method is Ruby's standard, built-in way to do a shallow-copy:
irb(main):003:0> h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):004:0> h1 = h0.clone
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
irb(main):005:0> h1["John"] = "Smith"
=> "Smith"
irb(main):006:0> h1
=> {"John"=>"Smith", "Thomas"=>"Jefferson"}
irb(main):007:0> h0
=> {"John"=>"Adams", "Thomas"=>"Jefferson"}
请注意,该行为可能被覆盖:
Note that the behavior may be overridden:
此方法可能具有类特定的行为。如果是这样,该行为将记录在该类的
#initialize_copy
方法下。
这篇关于如何在Ruby中复制散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!