添加到数组循环

时间:2012-06-28 02:52:39

标签: ruby arrays hash

Ruby代码是:

    a = []
    h = {}
    2.times.each do |i|
      %w(a b c).each do |x|
        h[x] = x + i.to_s
      end
      a << h
    end

结果是:

a = [{"c"=>"c1", "b"=>"b1", "a"=>"a1"}, {"c"=>"c1", "b"=>"b1", "a"=>"a1"}]

但我希望结果是:

a = [{"c"=>"c0", "b"=>"b0", "a"=>"a0"}, {"c"=>"c1", "b"=>"b1", "a"=>"a1"}]

谁可以帮助我.thx

2 个答案:

答案 0 :(得分:2)

a << h之后,您必须h = {}。这是因为您要为h分配一个新对象,以便它不会覆盖以前的值。

答案 1 :(得分:0)

[补充答案] 您熟悉functional programming的原则吗?

(0..1).map { |n| Hash[("a".."c").map { |c| [c, "#{c}#{n}"] }] }
#=> {"a"=>"a0", "b"=>"b0", "c"=>"c0"}, {"a"=>"a1", "b"=>"b1", "c"=>"c1"}]