How could I check to see if a word exists in a string, and return false if it doesn't, in ruby?
Solution 1
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 …
Solution 2
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
Solution 3
You could also do this:
str.downcase.include? "Some string".downcase
Solution 4
If all I'm looking for is a case=insensitive substring match I usually use:
str.downcase['do: ']
9 times out of 10 I don't care where in the string the match is, so this is nice and concise.
Here's what it looks like in IRB:
>> str = "Things to do: eat and sleep." #=> "Things to do: eat and sleep."
>> str.downcase['do: '] #=> "do: "
>> str.downcase['foobar'] #=> nil
Because it returns nil
if there is no hit it works in conditionals too.
Related videos on Youtube
oxo
Updated on April 05, 2020Comments
-
oxo about 4 years
Say I have a string
str = "Things to do: eat and sleep."
How could I check if
"do: "
exists in str, case insensitive? -
oxo about 13 yearsWould it be possible to do this in an if block? E.g. if str =~ /do: /i puts "yes" end
-
Konrad Rudolph about 13 years@oxo Yes of course. In fact, the first code is merely a shorthand of that.
-
PJP about 13 years"perhaps there is a way to skip the downcase part to get case insensitivity"?
str.match(/do: /i)
-
Michael Kohl about 13 yearsThere's also the good old
!!
trick to only get a boolean result:>> !!(str =~ /do:/i) #=> true
and>> !!(str =~ /da:/i) #=> false
. -
Jakob W about 13 years@theTinMan Oh, and it was even in the first answer as well. Need to think better next time =)
-
David J. over 11 yearsWhy do you need to force a boolean? In Ruby, any value can be treated as if it is truthy; e.g. true / false.
-
David J. over 11 yearsIf you are running many regexs that are case-insensitive, it might be more efficient to downcase once and then use many case-sensitive regexs.
-
Konrad Rudolph over 11 years@David Because that’s what the OP wanted. Normally I’d just use the expression directly, of course (see first example). But since the OP explicitly mentioned getting a boolean I showed how to do that, too.