How to check whether a string contains a substring in Ruby

后端 未结 9 970
南旧
南旧 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:18

    You can use the String Element Reference method which is []

    Inside the [] can either be a literal substring, an index, or a regex:

    > s='abcdefg'
    => "abcdefg"
    > s['a']
    => "a"
    > s['z']
    => nil
    

    Since nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

    0> if s[sub_s]
    1>    puts "\"#{s}\" has \"#{sub_s}\""
    1> else 
    1*    puts "\"#{s}\" does not have \"#{sub_s}\""
    1> end
    "abcdefg" has "abc"
    
    0> if s[sub_s]
    1>    puts "\"#{s}\" has \"#{sub_s}\""
    1> else 
    1*    puts "\"#{s}\" does not have \"#{sub_s}\""
    1> end
    "abcdefg" does not have "xyz" 
    

    Just make sure you don't confuse an index with a sub string:

    > '123456790'[8]    # integer is eighth element, or '0'
    => "0"              # would test as 'true' in Ruby
    > '123456790'['8']  
    => nil              # correct
    

    You can also use a regex:

    > s[/A/i]
    => "a"
    > s[/A/]
    => nil
    

提交回复
热议问题