72
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby - Hashをkey|valueでASC|DESCソート

72
Last updated at Posted at 2015-08-18

経緯

  • 一見、単純そうだが、クセがあるのでメモ。
  • 手法は幾つかあるらしいが、自分のお気に入りのみメモ。

ソートするデータ例

h = { "a" => 57, "c" => 81, "b" => 49, "d" => 77 }

keyでソート

ASC

Hash[ h.sort ]
#=> { "a" => 57, "b" => 49, "c" => 81, "d" => 77 }

DESC

Hash[ h.sort.reverse ]
#=> { "d" => 77, "c" => 81, "b" => 49, "a" => 57 }

valueでソート

ASC

Hash[ h.sort_by{ |_, v| v } ]
#=> { "b" => 49, "a" => 57, "d" => 77, "c" => 81 }

DESC

Hash[ h.sort_by{ |_, v| -v } ]
#=> { "c" => 81, "d" => 77, "a" => 57, "b" => 49 }

資料

72
56
0

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
72
56

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?