Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | String |

概要

String#<=> other -> -1 | 0 | 1 | nil

詳細

self と other を ASCII コード順で比較。
戻り値は以下のようになる。

self > other : 1
self == other : 0
self < other : -1

このメソッドは Comparable モジュールのメソッドを実装するために利用する。
other が文字列以外の場合は、 other#<=> を利用する。

サンプルコード
require 'tbpgr_utils'

class NumericCompare
  def initialize(number)
    @number = number
  end

  def <=>(other)
    @number <=> other.to_i
  end
end

bulk_puts_eval binding, <<-EOS
"hige" <=> "hage"
"hige" <=> "hige"
"hige" <=> "hoge"
"ほげ" <=> "ほが"
"ほげ" <=> "ほげ"
"ほげ" <=> "ほご"
"5" <=> NumericCompare.new(4)
"5" <=> NumericCompare.new(5)
"5" <=> NumericCompare.new(6)
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

"hige" <=> "hage"             # => 1
"hige" <=> "hige"             # => 0
"hige" <=> "hoge"             # => -1
"ほげ" <=> "ほが"             # => 1
"ほげ" <=> "ほげ"             # => 0
"ほげ" <=> "ほご"             # => -1
"5" <=> NumericCompare.new(4) # => 1
"5" <=> NumericCompare.new(5) # => 0
"5" <=> NumericCompare.new(6) # => -1