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

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

    As I wanted this to work generally, and not just for any specific project, I do not want to modify the environment at all.

    I was able to get it to work by simply using the return value from the normal match method as a conditional. Tested both the positive and negative case on this sample string:

    irb(main):014:0> if "123".match(/.2./); puts "worked"; end
    worked
    => nil
    irb(main):015:0> if "123".match(/.3./); puts "worked"; end
    => nil
    
    0 讨论(0)
  • 2021-02-18 19:12

    To make it return true/false switch the position of pattern and string and use case equality ===

    def has_regex?(string)
        pattern = /something/i
        return pattern === string
    end
    

    I absolutely needed it to return true boolean value and digged around. It is actually documented in regexp class http://www.ruby-doc.org/core-2.1.3/Regexp.html#method-i-3D-3D-3D

    0 讨论(0)
  • 2021-02-18 19:14

    If you want the put the pattern in a method, you can just do

    def has_my_pattern(st)
        st =~ /pattern/
    end
    

    Or, perhaps better, put the pattern in a class variable instead?

    0 讨论(0)
  • 2021-02-18 19:18

    For Ruby >= 2.4 or Rails, you can do:

     regexp.match?(string)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题