我承认我是一个红宝石新手(现在写rake脚本).在大多数语言中,复制构造函数很容易找到.半小时的搜索没有在红宝石中找到它.我想创建一个哈希的副本,以便我可以修改它而不影响原始实例.
一些预期的方法不能按预期工作:
h0 = { "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash
Run Code Online (Sandbox Code Playgroud)
与此同时,我采用了这种不优雅的解决方法
def copyhash(inputhash)
h = Hash.new
inputhash.each do |pair|
h.store(pair[0], pair[1])
end
return h
end
Run Code Online (Sandbox Code Playgroud)