Sort a nested hash in ruby

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

, , , , , , !

, , . . , , , , .. ..

+3
4
tag_hash = tag_hash.sort_by do |_, leaf|
  leaf.reject do |key, _|
    key == 4
  end.collect(&:last).inject(:+)
end
+8
my_hash.sort_by do |_, h|
  h.inject(0) do |sum, n|
    # only add to the sum if the key isn't '4'
    n[0] == 4 ? sum : (sum + n[1])
  end
end

, , :

my_hash.sort_by {|k,h| h.inject(0) {|sum,n| n[0] == 4 ? sum : (sum + n[1]) } }
+2

puts a.sort_by { |k, v| -v.values[0..-1].inject(&:+) }

: , ?

cat
{1=>2, 2=>10, 3=>11, 4=>1}
wings
{1=>3, 2=>5, 3=>7, 4=>7}
stubborn
{1=>5, 2=>3, 3=>7, 4=>5}
grimace
{1=>4, 2=>5, 3=>5, 4=>1}
0

:

x.sort_by{ |_,h| h.values.take(3).inject(:+) }

, ( - , ).

ActiveSupport, :

x.sort_by{ |_,h| h.values.take(3).sum }

x.sort_by{ |_,h| h.slice(1,2,3).values.sum }

Hash # slice returns a hash containing only the keys passed to the slice. Array # take returns an array containing the first n entries of the original array.

(requires Ruby 1.9.1)

0
source

Source: https://habr.com/ru/post/1741872/


All Articles