地方でリモートワーク

プログラミング、先物、fx,仮想通貨なんでもやります

Rubyでhashのソートの挙動のメモ

スポンサーリンク

ブロックの渡し方、参照の仕方のメモ

scores = { 'Carol' => 90, 'Alice' => 50, 'Bob' => 60, 'David' => 40 }
scores.sort {|(k1, v1), (k2, v2)| v2 <=> v1 } # => [["Carol", 90], ["Bob", 60], ["Alice", 50], ["David", 40]] # !> assigned but unused variable - k2
# valueのdesc
scores.sort {|(k1, v1), (k2, v2)| v1 <=> v2 } # => [["David", 40], ["Alice", 50], ["Bob", 60], ["Carol", 90]] # !> assigned but unused variable - k2
# valueのasc
scores.sort {|(k1, v1), (k2, v2)| k1 <=> k2 } # => [["Alice", 50], ["Bob", 60], ["Carol", 90], ["David", 40]] # !> assigned but unused variable - v2
# keyのasc
scores.sort {|(k1, v1), (k2, v2)| k2 <=> k1 } # => [["David", 40], ["Carol", 90], ["Bob", 60], ["Alice", 50]] # !> assigned but unused variable - v2
# keyのdesc
scores.sort { |key,value| key[1] <=> value[1] } # => [["David", 40], ["Alice", 50], ["Bob", 60], ["Carol", 90]]
# valueのasc
scores.sort { |key,value| value[1] <=> key[1] } # => [["Carol", 90], ["Bob", 60], ["Alice", 50], ["David", 40]]
# valueのdesc
scores.sort { |key,value| value[0] <=> key[0] } # => [["David", 40], ["Carol", 90], ["Bob", 60], ["Alice", 50]]
# keyのdesc
scores.sort { |key,value| key[0] <=> value[0] } # => [["Alice", 50], ["Bob", 60], ["Carol", 90], ["David", 40]]
# keyのasc