我承认我是一个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
clone方法是Ruby标准的、内置的浅复制方法:
h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1 = h0.clone
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1["John"] = "Smith"
# => "Smith"
h1
# => {"John"=>"Smith", "Thomas"=>"Jefferson"}
h0
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
注意,行为可能会被覆盖:
该方法可能具有特定于类的行为。如果是,该行为将记录在类的#initialize_copy方法下。
克隆很慢。为了提高性能,应该从空白散列和合并开始。不覆盖嵌套哈希的情况…
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)