此代码:/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以获取详细信息。