我承认我是一个ruby新手(现在正在编写rake脚本)。在大多数语言中,复制构造函数很容易找到。找了半个小时也没找到露比。我想创建一个散列的副本,这样我就可以在不影响原始实例的情况下修改它。
一些未按预期工作的预期方法:
h0 = { "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash
与此同时,我采用了这种不优雅的变通方法
def copyhash(inputhash)
h = Hash.new
inputhash.each do |pair|
h.store(pair[0], pair[1])
end
return h
end
克隆很慢。为了提高性能,应该从空白散列和合并开始。不覆盖嵌套哈希的情况…
require 'benchmark'
def bench Benchmark.bm do |b|
test = {'a' => 1, 'b' => 2, 'c' => 3, 4 => 'd'}
b.report 'clone' do
1_000_000.times do |i|
h = test.clone
h['new'] = 5
end
end
b.report 'merge' do
1_000_000.times do |i|
h = {}
h['new'] = 5
h.merge! test
end
end
b.report 'inject' do
1_000_000.times do |i|
h = test.inject({}) do |n, (k, v)|
n[k] = v;
n
end
h['new'] = 5
end
end
end
end
bench user system total ( real)
clone 1.960000 0.080000 2.040000 ( 2.029604)
merge 1.690000 0.080000 1.770000 ( 1.767828)
inject 3.120000 0.030000 3.150000 ( 3.152627)
如Marshal文档的安全考虑部分所述,
如果需要反序列化不受信任的数据,请使用JSON或其他格式
只能加载简单的“原始”的序列化格式
类型,如字符串,数组,哈希等。
下面是一个关于如何在Ruby中使用JSON进行克隆的例子:
require "json"
original = {"John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
cloned = JSON.parse(JSON.generate(original))
# Modify original hash
original["John"] << ' Sandler'
p original
#=> {"John"=>"Adams Sandler", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}
# cloned remains intact as it was deep copied
p cloned
#=> {"John"=>"Adams", "Thomas"=>"Jefferson", "Johny"=>"Appleseed"}