Descending sort by value of a Hash in Ruby

前端 未结 4 1449
花落未央
花落未央 2020-12-12 14:14

My input hash: h = { \"a\" => 20, \"b\" => 30, \"c\" => 10 }

Ascending sort: h.sort {|a,b| a[1]<=>b[1]} #=> [[\"c\", 10], [\"a

相关标签:
4条回答
  • 2020-12-12 14:39

    Super simple: h.sort_by { |k, v| -v }

    0 讨论(0)
  • 2020-12-12 14:40
    h.sort {|a,b| b[1]<=>a[1]}
    
    0 讨论(0)
  • 2020-12-12 14:56

    You can have it cleaner, clearer and faster, all at once! Like this:

    h.sort_by {|k,v| v}.reverse
    

    I benchmarked timings on 3000 iterations of sorting a 1000-element hash with random values, and got these times:

    h.sort {|x,y| -(x[1]<=>y[1])} -- 16.7s
    h.sort {|x,y| y[1] <=> x[1]} -- 12.3s
    h.sort_by {|k,v| -v} -- 5.9s
    h.sort_by {|k,v| v}.reverse -- 3.7
    
    0 讨论(0)
  • 2020-12-12 14:58

    <=> compares the two operands, returning -1 if the first is lower, 0 if they're equal and 1 if the first is higher. This means that you can just do -(a[1]<=>b[1]) to reverse the order.

    0 讨论(0)
提交回复
热议问题