簡體   English   中英

紅寶石匹配正則表達式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM