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

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

    Your code looks fine, but you could write it even smaller.

    The return value of String#=~ behaves this way:

    • nil if the pattern did not match
    • the position in the string where the matched word started

    In Ruby everything except nil and false behaves like true in a conditional statement so you can just write

    if string=~ pattern
      # do something
    else
      # panic
    end
    

提交回复
热议问题