0
0

sort_byメソッドについて

Posted at

sort_byメソッドについて

array,hashに対して使えるメソッド
ブロックに渡した、値をソートキーとし昇順に並び替えて返す
:::note info
ここで言う、ソートキーとは、要素に紐づけた値
数字だと、そのままの値がキーとなりなんの意味これ・・・?と思うが
lengthなどで考えてみるとわかりやすい
appleという値が飛んできた時に、こいつは5っていうソートキーを基準に比較するで・・・的な感じ
:::

このメソッドは破壊的なメソッドではないため、元のarray,hashを変更しない
変更をしたい場合は、sort_by!を使用する

### arrayの場合
const nums = [3, 2, 1, 4, 5]
nums.sort_by { |num| num }
 →[1, 2, 3, 4, 5]

### hashの場合
const ages = [{age: 1}, {age: 5}, {age: 3}]
ages.sort_by {|hash| hash[:age]}
 →[{age: 1}, {age: 3} {age: 5}]
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