如何在 Ruby 中复制哈希? [英] How do I copy a hash in Ruby?
问题描述
我承认我有点像 ruby 新手(现在正在编写 rake 脚本).在大多数语言中,很容易找到复制构造函数.找了半个小时没在ruby里找到.我想创建一个散列的副本,这样我就可以在不影响原始实例的情况下修改它.
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
推荐答案
clone
方法是 Ruby 的标准内置方法来执行 浅拷贝:
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
方法下.
This method may have class-specific behavior. If so, that behavior will be documented under the
#initialize_copy
method of the class.
这篇关于如何在 Ruby 中复制哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!