Tbpgr Blog

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

Ruby | String | =~

概要

String#=~ other -> Integer

詳細

正規表現 other とのマッチを実行。

マッチが成功: マッチした位置のインデックス
マッチが失敗: nil

を返却。
other が正規表現でも文字列でもない場合は other =~ self を行います。

このメソッドが実行されると、組み込み変数 $~, $1, ... にマッチに関する情報が設定されます。

サンプルコード
require 'tbpgr_utils'

class Matchable
  def initialize(value)
    @value = value
  end

  def =~(other)
    /.*#{@value}.*/ =~ other.to_s
  end
end

bulk_puts_eval binding, <<-EOS
"hoge" =~ /h.ge/
"ahoge" =~ /h.ge/
"hogehigehage" =~ /(h.ge)(h.ge)(h.ge)/
Regexp.last_match
"bar" =~ /h.ge/
"tanaka" =~ Matchable.new('tanaka')
"ichiro tanaka" =~ Matchable.new('tanaka')
"tanaka ichiro" =~ Matchable.new('tanaka')
"suzuki ichiro" =~ Matchable.new('tanaka')
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

"hoge" =~ /h.ge/                           # => 0
"ahoge" =~ /h.ge/                          # => 1
"hogehigehage" =~ /(h.ge)(h.ge)(h.ge)/     # => 0
Regexp.last_match                          # => #<MatchData "hogehigehage" 1:"hoge" 2:"hige" 3:"hage">
"bar" =~ /h.ge/                            # => nil
"tanaka" =~ Matchable.new('tanaka')        # => 0
"ichiro tanaka" =~ Matchable.new('tanaka') # => 0
"tanaka ichiro" =~ Matchable.new('tanaka') # => 0
"suzuki ichiro" =~ Matchable.new('tanaka') # => nil