Ruby: What's the proper syntax for a boolean regex method?

前端 未结 10 2400
野趣味
野趣味 2021-02-18 18:40

What is the proper syntax for a method that checks a string for a pattern, and returns true or false if the regex matches?

Basic idea:

def has_regex?(str         


        
相关标签:
10条回答
  • 2021-02-18 19:24

    In the question you said:

    ... method that checks a string for a pattern, and returns true or false if the regex matches

    As johannes pointed out String=~ returns nil if the pattern did not match and the position in the string where the matched word stared otherwise. Further he states in Ruby everything except nil and false behave like true. All of this is right.

    However, they are not exactly true or false. Therefore, the last step is to coerce the value to be a Boolean. This is achieved by wrapping the result in double bangs returns a true.

    def has_regex?(string)
        !!(string =~ /something/i)
    end
    
    0 讨论(0)
  • 2021-02-18 19:28

    Adding this to the String class makes it pretty simple to use:

       class String
          def match?(regex)
              !!self.match(regex)
          end
       end
    

    I added it to Rails initializer (RAILS_ROOT/config/initializers) and you can call directly from the string:

    "Something special!".match?(/something/i) #=> true 
    "Somethin' special!".match?(/something/i) #=> false 
    
    0 讨论(0)
  • 2021-02-18 19:31

    If you are using Ruby 2.4 or later, there are String#match?(regex) and Regexp#match?(string) methods that return booleans without the conversion shenanigans (where needed, usually not), and have improved performance to boot.

    https://ruby-doc.org/core-2.4.0/Regexp.html#method-i-match-3F

    https://blog.cognitohq.com/new-features-in-ruby-2-4/

    0 讨论(0)
  • 2021-02-18 19:31

    I do not have enough reputation to comment, so I will answer instead.

    Use of ===, as suggested by viljar, is advised against in the Ruby Style Guide and will cause Rubocop complaints (under default rules).

    I find the most readable way to be:

    def match?(string)
      !(string =~ /something/i).nil?
    end
    
    0 讨论(0)
提交回复
热议问题