How to check whether a string contains a substring in Ruby

后端 未结 9 971
南旧
南旧 2020-11-28 18:02

I have a string variable with content:

varMessage =   
            \"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\\n\"


            \"/my/name/is/balaji.so\\n\"
                 


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 18:05

    Expanding on Clint Pachl's answer:

    Regex matching in Ruby returns nil when the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

    "foobar" =~ /bar/  # returns 3
    "foobar" =~ /foo/  # returns 0
    "foobar" =~ /zzz/  # returns nil
    

    It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.

    That's why the /foo/ example above works, and why.

    if "string" =~ /regex/
    

    works as expected, only entering the 'true' part of the if block if a match occurred.

提交回复
热议问题