Descending sort by value of a Hash in Ruby

前端 未结 4 1453
花落未央
花落未央 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: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.

提交回复
热议问题