0
0

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 1 year has passed since last update.

booleanはsortのキーに使えないのか

Posted at

何番煎じか分かりませんが、ちょっと面白かったのでメモがてら書いてみます。

data = [
  {flag: true, score: 30},
  {flag: false, score: 20},
  {flag: true, score: 10},
  {flag: false, score: 40}
]

# こういうデータがある時、条件1: trueを上に、条件2: スコア順でソートしたい

data.sort_by { |item| [item[:flag], item[:score]] }
# => ArgumentError: comparison of Array with Array failed

# むむ? キーをflagだけにすると...
data.sort_by { |item| item[:flag] }
# => ArgumentError: comparison of TrueClass with false failed

# なるほど! TrueClassとFlaseClassで比較はできないよってことね

# ということは... これならいけそう
data.sort_by { |item| [item[:flag] ? 0 : 1, item[:score]] }
# => [{:flag=>true, :score=>10}, {:flag=>true, :score=>30}, {:flag=>false, :score=>20}, {:flag=>false, :score=>40}]

# 良さそう! だけどscoreは降順にしたいな。
data.sort_by { |item| [item[:flag] ? 0 : 1, -item[:score]] }
# => [{:flag=>true, :score=>30}, {:flag=>true, :score=>10}, {:flag=>false, :score=>40}, {:flag=>false, :score=>20}]
# 🎊

# 別解. こっちの方が好きっていう人もいそう
data.partition{|i| i[:flag] }.map{|unit| unit.sort_by {|i| -i[:score] }}.flatten

item[:flag] ? 0 : 1 がダサいなーと思いつつ妙案が浮かばなかったでござる。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?