How to check whether a string contains a substring in Ruby

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

    You can also do this...

    my_string = "Hello world"
    
    if my_string["Hello"]
      puts 'It has "Hello"'
    else
      puts 'No "Hello" found'
    end
    
    # => 'It has "Hello"'
    

    This example uses Ruby's String #[] method.

    0 讨论(0)
  • 2020-11-28 18:22

    Ternary way

    my_string.include?('ahr') ? (puts 'String includes ahr') : (puts 'String does not include ahr')
    

    OR

    puts (my_string.include?('ahr') ? 'String includes ahr' : 'String not includes ahr')
    
    0 讨论(0)
  • 2020-11-28 18:26
    user_input = gets.chomp
    user_input.downcase!
    
    if user_input.include?('substring')
      # Do something
    end
    

    This will help you check if the string contains substring or not

    puts "Enter a string"
    user_input = gets.chomp  # Ex: Tommy
    user_input.downcase!    #  tommy
    
    
    if user_input.include?('s')
        puts "Found"
    else
        puts "Not found"
    end
    
    0 讨论(0)
提交回复
热议问题