!~ 演算子とは

文字列と正規表現パターンを比較して、そのパターンがその文字列のどこにも含まれていないかどうかを調べます。(http://www.dataondemand.co.jp/documents/data_integrator814/rifl_language/Does_Not_Contain_Operator.html)

 

と記載してあるが、一体どういうことなのか具体的に調べてみた。

 

aa = "abc333333"
bb = "333abc333333"

puts aa !~ /abc/

puts bb !~ /abc/

puts bb !~ /^abc/

puts aa !~ /xxx/

puts bb !~ /^[abc]/

puts aa !~ /^[abc]/

if aa !~ /abc/
  puts "hello"
else 
  puts "jamp"
end

unless aa !~ /abc/
  puts "hello"
else 
  puts "jamp"
end

if bb !~ /^abc/
  puts "hello"
else 
  puts "jamp"
end

unless bb !~ /^abc/
  puts "hello"
else 
  puts "jamp"
end

このコードを書いて出力してみたところ

 

$ ruby practice.rb

false

false

true

true

true

false

jamp

hello

hello

jamp

 

という結果がでた