0

I was trying to create an array of hashes, to which i have already found some excellent solutions here:

Creating array of hashes in ruby

However while trying it out on my own, i found some behavior which i didn't understand.

Creating an array of hashes in IRB:

array_hashes = Array.new(7, Hash.new)

Now, on trying to assign key, value pairs to the array:

array_hashes[1]["hello"] = 200

I got the following output in console:

=>[{"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}]

The same key , value was repeated across all the array elements, similar results when i tried to assign another key, value to a single array element

array_hashes[3]["world"] = 300
=>[{"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}] 

Can anyone explain the reason for this, specifically why are hash values repeated across all the array elements even on being assigned to a single element. Thanks!

Ruby Version used: 1.9.3, tried on Windows 7 and OS X Yosemite

1
  • 3
    This has been asked many times before here on SO. The short answer is: read the docs for Array::new, they even contain the exact example you are asking about. Commented Dec 10, 2014 at 17:55

1 Answer 1

3

It's repeated because what this code does:

array_hashes = Array.new(7, Hash.new)

Is this:

hash = Hash.new
array_hashes = [hash, hash, hash, hash, hash, hash, hash]

So it's the same object included 7 times in the array.

But what you wanted to do was:

array_hashes = Array.new(7) { Hash.new }
Sign up to request clarification or add additional context in comments.

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.