Sorting nested hash in ruby

Posted by Rabbott on Stack Overflow See other posts from Stack Overflow or by Rabbott
Published on 2010-04-20T02:10:17Z Indexed on 2010/04/20 2:13 UTC
Read the original article Hit count: 341

Filed under:
|
|

Provided the following ruby hash:

{
    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 instance the value to compare for "cat" would be (2 + 10 + 11) = 23, the value for "wings" would be (3 + 5 + 7) = 15 so if I was comparing just those two they would be in the correct order, highest sum on top.

It is safe to assume that it will ALWAYS be {1: value, 2: value, 3: value, 4: value} as those are keys for constants I have defined.

It is also safe to assume that I will only ever want to exclude the key "4", and always use the keys "1", "2", and "3"

© Stack Overflow or respective owner

Related posts about ruby

Related posts about sorting