Tbpgr Blog

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

Ruby | String | ==

概要

String#self == other -> bool
String#self === other -> bool

詳細

other が文字列の場合、文字列の内容を比較( String#eql? と同じ)。
other が文字列でない場合、 other.to_str が定義されていれば other == self の結果を返します。
(ただし、 other.to_str は実行されません。) そうでなければ false を返します。

サンプルコード
require 'tbpgr_utils'

bulk_puts_eval binding, <<-EOS
"hoge" == "hoge"
"hoge" == String.new("hoge")
"hoge".eql?(String.new("hoge"))
"hoge".equal?(String.new("hoge"))
"1" == 1
EOS

class Fixnum
  def ==(other)
    self.to_s == other
  end

  def to_str
    number.to_s
  end
end

bulk_puts_eval binding, <<-EOS
"1" == 1
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

"hoge" == "hoge"                  # => true
"hoge" == String.new("hoge")      # => true
"hoge".eql?(String.new("hoge"))   # => true
"hoge".equal?(String.new("hoge")) # => false
"1" == 1                          # => false
"1" == 1                          # => true