9
6

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のsort_byを使って配列を特定の順番に並び替え

Last updated at Posted at 2019-08-29

Rubyのsort_byで特定の順番に並び替え

昇順や降順に並び替えるのは、よくありますが、
プロデューサーの意向で特定の順番に並び替えたい時があります。

例えば、人気順に並び替えたい時などです。

id 順ではなく、とにかく指定した順番に並び替えたい :thinking:

例えば、こんな配列があって、


@fruites = [
  [ 1, 'apple' ],
  [ 2, 'orange' ],
  [ 3, 'banana' ],
  [ 4, 'melon' ],
  [ 5, 'peach' ],
  [ 6, 'kiwi' ],
  [ 7, 'cherry' ],
]

こんな id順で指定されたとします :arrow_down:


FRUITS_ORDER = [3, 2, 7, 5, 4, 1, 6]

sort_by に、並び替えたいid順におけるindex(位置情報)を渡してあげると、その通りに並び替えられます :relieved:


@fruites.sort_by{|fruit| FRUITS_ORDER.index(fruit[0])}
=> [[3, "banana"],
 [2, "orange"],
 [7, "cherry"],
 [5, "peach"],
 [4, "melon"],
 [1, "apple"],
 [6, "kiwi"]]
9
6
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
9
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?