Posted by: capehart | November 1, 2010

On Ruby Hashes

Suppose we are to create an array of hashes in ruby like so:

a = []
h = {:a=”a”}
a << h
h[:a] = “b”
a << h
h[:a] = ‘c”
a << h

What will the array contain? Interestingly, it will contain [{:a=>"c"}, {:a=>"c"}, {:a=>"c"}].

This shows that appending the hash into the array is by reference.

When I had to do something like this I used this very simple work around:

a = []
h = {:a=”a”}
a << Hash[h]
h[:a] = “b”
a << Hash[h]
h[:a] = ‘c”
a << Hash[h]

This causes a new hash to be created and assigned with each append.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.