Tbpgr Blog

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

Ruby | Regexp | ===

概要

Regexp#=== string -> bool

詳細

文字列 string との正規表現マッチを行い、 マッチした場合は真を返却します。
string が文字列でもシンボルでもない場合には false を返します。

るりまには記載されていないが、 Regexp#=== は
case 文の内部での利用を想定されていると思われる。

サンプルコード
require 'tbpgr_utils'

bulk_puts_eval binding, <<-EOS
/h.ge/==="hoge"
/h.ge/==="hige"
/h.ge/==="hig"
Regexp.compile(/h.ge/)==="hoge"
Regexp.compile(/h.ge/)==="hige"
Regexp.compile(/h.ge/)==="hig"
EOS

def sample(msg)
  case msg
  when /h.ge/
    "match h.ge : #{msg}"
  when /ほげ/
    "match ほげ : #{msg}"
  else
    "not match"
  end
end

bulk_puts_eval binding, <<-EOS
sample('hoge')
sample('hige')
sample('ほげ')
sample('ほげりん')
sample('はげ')
sample('hig')
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

/h.ge/==="hoge"                 # => true
/h.ge/==="hige"                 # => true
/h.ge/==="hig"                  # => false
Regexp.compile(/h.ge/)==="hoge" # => true
Regexp.compile(/h.ge/)==="hige" # => true
Regexp.compile(/h.ge/)==="hig"  # => false
sample('hoge')     # => "match h.ge : hoge"
sample('hige')     # => "match h.ge : hige"
sample('ほげ')     # => "match ほげ : ほげ"
sample('ほげりん') # => "match ほげ : ほげりん"
sample('はげ')     # => "not match"
sample('hig')      # => "not match"