例如,我有单个哈希数组
a = [{a: :b}, {c: :d}]
将其转换为此的最佳方法是什么?
{a: :b, c: :d}
Answers:
我遇到了这个答案,我想从性能上比较这两个选项,以查看哪个更好:
a.reduce Hash.new, :merge
a.inject(:merge)
使用ruby基准测试模块,结果表明该选项(2) a.inject(:merge)
更快。
用于比较的代码:
require 'benchmark'
input = [{b: "c"}, {e: "f"}, {h: "i"}, {k: "l"}]
n = 50_000
Benchmark.bm do |benchmark|
benchmark.report("reduce") do
n.times do
input.reduce Hash.new, :merge
end
end
benchmark.report("inject") do
n.times do
input.inject(:merge)
end
end
end
结果是
user system total real
reduce 0.125098 0.003690 0.128788 ( 0.129617)
inject 0.078262 0.001439 0.079701 ( 0.080383)
尝试这个
a.inject({}){|acc, hash| acc.merge(hash)} #=> {:a=>:b, :c=>:d}
Hash.new
,或者作为朋友喜欢给他打电话,{}
:-)就像我喜欢纯功能解决方案一样,请注意,merge
它将在每次迭代中创建一个新的哈希;我们可以update
改用(它不会弄乱输入的哈希值,这很重要):hs.reduce({}, :update)