要散列的哈希数组

时间:2012-06-08 06:18:30

标签: ruby arrays hash

例如,我有一系列单个哈希

a = [{a: :b}, {c: :d}]

将它转换成这个的最佳方法是什么?

{a: :b, c: :d}

7 个答案:

答案 0 :(得分:109)

您可以使用

a.reduce Hash.new, :merge

直接产生

{:a=>:b, :c=>:d}

请注意,如果发生碰撞,订单很重要。后置哈希覆盖以前的映射,例如:

[{a: :b}, {c: :d}, {e: :f, a: :g}].reduce Hash.new, :merge   # {:a=>:g, :c=>:d, :e=>:f}

答案 1 :(得分:33)

您可以使用 if (Ext.os.is('Android')) { document.addEventListener("backbutton", Ext.bind(onBackKeyDown, this), false); function onBackKeyDown(eve) { eve.preventDefault(); Ext.Msg.confirm('Test',"Are you Want Quit Application", function (btn) { switch (btn) { case 'yes': WL.Client.reloadApp(); // this is i am using but i dnt want this. break; default: break; } }); } }

.inject

Demonstration

从两个合并的每次迭代中启动一个新的哈希。为避免这种情况,您可以使用破坏性a.inject(:merge) #=> {:a=>:b, :c=>:d} (或:merge!,这是相同的):

:update

Demonstration

答案 2 :(得分:21)

这两个:

total_hash = hs.reduce({}) { |acc_hash, hash| acc_hash.merge(hash) }
total_hash = hs.reduce({}, :merge)

请注意,Hash#merge会在每次迭代时创建一个新哈希,如果您要构建一个大哈希,这可能会有问题。在这种情况下,请改用update

total_hash = hs.reduce({}, :update)

另一种方法是将散列转换为对,然后构建最终散列:

total_hash = hs.flat_map(&:to_a).to_h

答案 3 :(得分:0)

试试这个

a.inject({}){|acc, hash| acc.merge(hash)} #=> {:a=>:b, :c=>:d}

答案 4 :(得分:0)

只需使用

a.reduce(:merge)
#=> {:a=>:b, :c=>:d}

答案 5 :(得分:0)

我遇到了这个答案,我想比较两种选择的性能,以查看哪种更好:

  1. a.reduce Hash.new, :merge
  2. 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)

答案 6 :(得分:0)

您可以将其转换为数组[[:a, :b]],然后将所有内容转换为哈希{:a=>:b}

# it works like [[:a, :b]].to_h => {:a=>:b}

[{a: :b}, {c: :d}].map { |hash| hash.to_a.flatten }.to_h

# => {:a=>:b, :c=>:d}