1
1

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 5 years have passed since last update.

スペースシップ演算子についてのメモ

Posted at

Rubyのsortメソッドを使用していると、<=>の表記をよく目にする。
これはスペースシップ演算子(又は、宇宙船演算子)と呼ばれるものらしい。
2つの値を比較して下記の値を返す。

  • 左辺の値よりも右辺の値が大きければ負の数
  • 左辺の値と右辺の値が等しければ0
  • 左辺の値が右辺の値よりも大きければ正の数
1 <=> 2		# => -1
1 <=> 1		# => 0
1 <=> 0		# => 1

使用例

  • 各配列の数値を昇順に並べる。
%w(100 300 200 500 400 200).map(&:to_i).sort { |a,b| a <=> b }
# => [100, 200, 200, 300, 400, 500]
  • 各配列の文字列から文字数の少ない順に並べる。
%w(Alice Bob John FooBar).sort{ |a,b| a.length <=> b.length }
# => ["Bob", "John", "Alice", "FooBar"]

参考

パーフェクトRuby

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?