Ruby で <=> 演算子でソートする
Ruby
Published: 2019-05-06

やったこと

Ruby でソートする方法について調べました。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

調査

<=> 演算子について

<=>演算子(メソッド)は、2つの配列の順序を調べます

$ irb
irb(main):001:0> 1 <=> 2
=> -1
irb(main):002:0> 2 <=> 1
=> 1
irb(main):003:0> 1 <=> 1
=> 0
$ irb
irb(main):001:0> ary1 = ['d', 'a', 'e', 'c', 'b']
=> ["d", "a", "e", "c", "b"]
irb(main):002:0> p ary1.sort
["a", "b", "c", "d", "e"]
=> ["a", "b", "c", "d", "e"]
irb(main):003:0> ary2 = [9, 7, 10, 11, 8]
=> [9, 7, 10, 11, 8]
irb(main):004:0> p ary2.sort
[7, 8, 9, 10, 11]
=> [7, 8, 9, 10, 11]
irb(main):005:0> p ary2.sort{|a, b| a <=> b}
[7, 8, 9, 10, 11]
=> [7, 8, 9, 10, 11]
irb(main):006:0> p ary2.sort{|a, b| b <=> a}
[11, 10, 9, 8, 7]
=> [11, 10, 9, 8, 7]

参考