Topic: Array of hashes

Having
item = {"value1" = 0, "value2"="default"}
data =[]

doing
1.upto(10) do |index|
item["value1"] = index
data << item
end

I would expect data to have 10 hashes where "value1" is 1,2,3..10, however all the hashes in data have "value1" = 10, looks like everytime that item is updated, the value is updated for all the hashes already in the data array..

How to go about this?

Thanks

Re: Array of hashes

The variable item refrences the same hash object so that's why the data array will have the latest modified hash.

you can do this to get around it

item = {"value1"=>0, "value2"=>"default"}
data = []

1.upto(10) do |index|
  data << item.merge("value1" => index)
end

Hash#merge gives you a new hash object leaving the old one unmodified. You would have to do something more fancy if you want the item hash to be modified at the end of the loop.

Last edited by Kentor (2010-07-26 20:18:13)

Re: Array of hashes

here's an alternate one liner

(1..10).to_a.collect{|n| {"value1"=>n, "value2"=>"default"} }

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams