The following ruby hash is provided:
{
cat: {
1: 2,
2: 10,
3: 11,
4: 1
},
wings: {
1: 3,
2: 5,
3: 7,
4: 7
},
grimace: {
1: 4,
2: 5,
3: 5,
4: 1
},
stubborn: {
1: 5,
2: 3,
3: 7,
4: 5
}
}
How can I sort the hash by the sum of "leaf", excluding "4", for example, the value for comparison for "cat" would be (2 + 10 + 11) = 23, the value for "wings" (3 + 5 + 7) = 15, therefore, if I were to compare only these two, they would be in the correct order, the highest amount on top.
It is safe to assume that it will ALWAYS be {1: value, 2: value, 3: value, 4: value}, since these are the keys for the constants that I defined.
It is also safe to assume that I only want to exclude the key "4" and always use the keys "1", "2" and "3"
Based on Jordan, I got this to work:
tag_hash = tag_hash.sort_by do |h|
h[1].inject(0) do |sum, n|
n[0] == 4 ? sum : sum + (n[1] || 0)
end
end
, , , , , , !
, , . . , , , , .. ..