[英]ruby match regular expression
我试图要求文件夹中的所有文件。 我有以下几点。
Dir.foreach File.expand_path("app/models") do |file|
require file unless file === /^\./
end
但是,它失败了。 打开红宝石控制台时,请尝试以下操作:
"." === /^\./
它的值为假。 为什么不匹配?
===
运算符实际上是左侧对象的方法。
在这种情况下,操作数在===
上的顺序很重要,因为如果字符串文字为"."
首先,将计算String相等运算符(方法) String#===
。 如果将正则表达式文字放在左侧, 则使用Regexp运算符Regexp#===
:
反转您的操作数。
# The string "." isn't equal to the Regexp object
>> "." === /^\./
=> false
# With the regexp as the left operand:
>> /^\./ === "."
=> true
# With the string on the left, you may use =~ and test for nil as a non-match
>> "." =~ /^\./
=> 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.