1

Ruby code is:

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

the result is:

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

but i hope the result is:

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

who can help me.thx

2 Answers 2

2

After a << h you have to do h = {}. This is because you are assigning a new object to h so that it doesn't override the previous values.

Sign up to request clarification or add additional context in comments.

Comments

0

[Complementary answer] Are you familiar with the principles of 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"}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.