2013-11-23 49 views
-1

此代码:/ell/==='Hello'在Ruby中为true。为什么?

/ell/ === 'Hello' 

演算值为 '真' 的IRB。

我不明白为什么这在逻辑上合理。 Integer === 30是有意义的,因为30是Integer类的一部分,但字符串'Hello'是什么方式的一部分/ ell /?我不明白。

回答

1

在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

1

===文档案例操作员,它主要用于案例陈述,不应该被自己看到。

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"] 

任何其他不鼓励使用,它真的不需要任何意义。

0

正则表达式描述了一种语言,即一组字符串。 ===检查字符串是否为该组的成员。

请参阅my answer以获取详细信息。

相关问题