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

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

    For anyone's future reference, double bangs are frowned upon from bbatsov's ruby style guide. Instead of using a double bang, just check if the value isn't nil. If the value isn't nil, it exists.

    Instead of doing this:

    def has_regex?(string)
      !!(string =~ /something/i)
    end
    

    You can always do this:

    def has_regex?(string)
      !(string =~ /something/i).nil?
    end
    

提交回复
热议问题