1

Ruby代码是:</p>

    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

4

2 回答 2

2

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

于 2012-06-28T03:00:32.093 回答
0

【补充回答】你熟悉函数式编程的原理吗?

(0..1).map { |n| Hash[("a".."c").map { |c| [c, "#{c}#{n}"] }] }
#=> {"a"=>"a0", "b"=>"b0", "c"=>"c0"}, {"a"=>"a1", "b"=>"b1", "c"=>"c1"}]
于 2012-06-28T12:19:58.943 回答