Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I check to see if a word exists in a string, and return false if it doesn't, in ruby?

Say I have a string str = "Things to do: eat and sleep."

How could I check if "do: " exists in str, case insensitive?

like image 967
oxo Avatar asked Apr 04 '11 13:04

oxo


2 Answers

Like this:

puts "yes" if str =~ /do:/i

To return a boolean value (from a method, presumably), compare the result of the match to nil:

def has_do(str)
    (str =~ /do:/i) != nil
end

Or, if you don’t like the != nil then you can use !~ instead of =~ and negate the result:

def has_do(str)
    not str !~ /do:/i
end

But I don’t really like double negations …

like image 163
Konrad Rudolph Avatar answered Oct 14 '22 23:10

Konrad Rudolph


In ruby 1.9 you can do like this:

str.downcase.match("do: ") do   
  puts "yes" 
end

It's not exactly what you asked for, but I noticed a comment to another answer. If you don't mind using regular expressions when matching the string, perhaps there is a way to skip the downcase part to get case insensitivity.

For more info, see String#match

like image 22
Jakob W Avatar answered Oct 15 '22 00:10

Jakob W