I am creating a list of hashes in an array and would like to keep a count if they are the same.
Here is what an example hash looks like:
data = {
s: y.id,
t: z.id,
count: 0
}
I am iterating through a bunch of these hashes and pushing them onto a list. I would like it so that when the values for s
and t
already exist in a hash in the list, the count
would be incremented.
Let me clarify. Suppose this is my @list
@list = [
{
s: 1,
t: 2,
count: 5
},
{
s: 1,
t: 3,
count: 5
}
]
Now suppose, I want to push the following hash to the list:
data = {
s: 1,
t: 2,
count: 0
}
The result of @list should look like this because the hash with s==1
and t==2
already exists in the list:
@list = [
{
s: 1,
t: 2,
count: 6
},
{
s: 1,
t: 3,
count: 5
}
]
This is where I am currently.
@final = []
while widgets.count > 1
widget = widgets.shift
widgets.each do |w|
data = {
s: widget.id,
t: w.id,
count: 0
}
@final << data
end
end
This simply adds all the permutations to the list but I want to prevent the dups when s
and t
are identical and simply increment count
.
I hope I am clear.
Any suggestions would be greatly appreciated.