Tuesday 16 July 2013

Hash default array

Trying to do something in Ruby on Rails I just encountered the following problem:

I just had this:

hash = Hash.new([])
for...
    hash[key] << value
end

to make the default value a new array. I have since realised that this does not work as it uses the same array for each key in the hash. Meaning that every key returns the same array with all the values.

The way I worked round it was as follows:

hash = {}
for...
    arr = hash[group._id] || []
    arr << value
    hash[group._id] = arr
end

No comments:

Post a Comment