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

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

提交回复
热议问题