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

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

提交回复
热议问题