Finding if a sentence contains a specific phrase in Ruby

后端 未结 4 1960
不思量自难忘°
不思量自难忘° 2020-12-10 00:06

Right now I am seeing if a sentence contains a specific word by splitting the sentence into an array and then doing an include to see if it contains the word. Something lik

4条回答
  •  -上瘾入骨i
    2020-12-10 00:31

    If you're not familiar with regular expressions, I believe they can solve your problem here:

    http://www.regular-expressions.info/ruby.html

    Basically you'll create a regular expression object looking for "awesome" (most likely case insensitive) and then you can do

    /regex/.match(string)
    

    To return match data. If you want to return the index the character is at you can do this:

    match = "This is my awesome sentence." =~ /awesome/
    puts match   #This will return the index of the first letter, so the first a in awesome
    

    I'd read the article for more details though as it explains it better than I would. If you don't want to understand it as much and just want to jump into using it, I'd recommend this:

    http://www.ruby-doc.org/core/classes/Regexp.html

提交回复
热议问题