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

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

提交回复
热议问题