1

I'm trying to require all the files in a folder. I have the following.

    Dir.foreach File.expand_path("app/models") do |file|
        require file unless file === /^\./
    end

However, it's failing. When I open up a ruby console, I try the following:

"." === /^\./

and it evaluates to false. Why won't it match?

Hugo
  • 2,186
  • 8
  • 28
  • 44
  • That's just the way I've always done regex matching. I didn't realize that I had the operands flipped around though. – Hugo Aug 17 '14 at 22:54
  • That's perhaps an argument for using `=~`, as order makes no difference: `r = /^\./; ".ab" =~ r #=> 0; r =~ ".ab" #=> 0`. – Cary Swoveland Aug 17 '14 at 23:51

1 Answers1

1

The === operator is actually a method of the object on the left.

The order of operands on the === matters in this case, because if the string literal "." comes first, the String equality operator (method) String#=== is evaluated. If the regex literal is placed on the left, the Regexp operator Regexp#=== is used:

Reverse your operands.

# 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
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390