0
0

More than 3 years have passed since last update.

[Ruby] Hash で Value を昇順にする時 Key も昇順にする

Last updated at Posted at 2020-01-20

どういう並べ替えをする方法なの?

value を昇順に並べ替えた上で、 同じ value を持つ key についても昇順にする方法です。

具体的には、

# これを
{3: 10, 2: 20, 1: 10}

# こうする
{1: 10, 3: 10, 2: 20}

方法です。

方法

追記

コメントでこちらの方が簡単だと教えていただきました。

hash.sort_by{ |k, v| [v, k] }.to_h

仕組みはよく分かりませんが、いろいろ試した所出来たので投稿します。

# いったん Array に変換
array = hash.to_a

# key value を同時に昇順に変換
array.sort_by! {|x| [x[1], x[0]]}

# Hash に戻す
hash = array.to_h

参考:Rubyでの安定したソート| 8番目の光

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0