Reputation: 253
I have the following string
str = "feminino blue"
I need to know if there is a string called "mini" inside this string. When I use include? method, the return is true because "feMINino" has "min" Is there a way to search for the exact word that is passed as param?
Thanks
Upvotes: 0
Views: 240
Reputation: 70267
Sounds like a use case for regular expressions, which can match all kinds of more complex string patterns. You can read through that page for all the specifics (and it's very valuable to learn, not just as a Ruby concept; Regexes are used in almost every modern language), but this should cover your use case.
/\bmini\b/ =~ str
\b
means "match a word boundary", so exactly one of the things to the left or right should be a word character and the other side should not (i.e. should be whitespace or the beginning/end of the string).
This will return nil
if there's no match or the index of the match if there is one. Since nil
is falsy and all numbers are truthy, this return value is safe to use in an if
statement if all you need is a yes/no answer.
If the string you're working with is not constant and is instead in a variable called, say, my_word
, you can interpolate it.
/\b#{Regexp.quote(my_word)}\b/ =~ str
Upvotes: 1