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

前端 未结 10 2596
野趣味
野趣味 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: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 
    

提交回复
热议问题