此代碼:/ell/==='Hello'在Ruby中爲true。爲什麼?
/ell/ === 'Hello'
演算值爲 '真' 的IRB。
我不明白爲什麼這在邏輯上合理。 Integer === 30是有意義的,因爲30是Integer類的一部分,但字符串'Hello'是什麼方式的一部分/ ell /?我不明白。
此代碼:/ell/==='Hello'在Ruby中爲true。爲什麼?
/ell/ === 'Hello'
演算值爲 '真' 的IRB。
我不明白爲什麼這在邏輯上合理。 Integer === 30是有意義的,因爲30是Integer類的一部分,但字符串'Hello'是什麼方式的一部分/ ell /?我不明白。
語義上你說正則表達式'ell'匹配字符串'Hello'。由於'你好'包含子字符串'埃爾',這是真的。
這裏描述的 '===' 方法: http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-i-3D-3D-3D
在Ruby中,你不應該使用===
的任何東西,除了平等的情況下,找到Regex#===
Following a regular expression literal with the === operator allows you to compare against a String.
/^[a-z]$/ === "HELLO" #=> false /^[A-Z]$/ === "HELLO" #=> true
的===
文檔案例操作員,它主要用於案例陳述,不應該被自己看到。
case my_string
when /ll/ then puts 'the string migth be hello'
when /x/ then puts 'all i know is that the sting contain x'
else puts 'I have no idea'
end
它也可以在一些其他功能,如grep的使用:
array = ['ll', 'aa', 'hello']
p array.grep(/ll/){|x| x.upcase} #=> ["LL", "HELLO"]
任何其他不鼓勵使用,它真的不需要任何意義。
正則表達式描述了一種語言,即一組字符串。 ===
檢查字符串是否爲該組的成員。
請參閱my answer以獲取詳細信息。