appleLover
appleLover

Reputation: 15701

Match From a Group of Words

def has_word?
  text =~ /((Word1)|(Word2))/
end

This is what I do now and it works but I feel like there is a better ruby solution. What's the right way to do this?

Upvotes: 1

Views: 147

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

You may have some special situations to solve that aren't covered by your current approach. Here are some common solutions for these types of

Match regardless of case

/Word1|Word2/i

Avoid finding a match in the middle of a word

/\b(Word1|Word2)\b/

Match only the exact string

/^(Word1|Word2)$/

Matching variable lists of strings

def get_match(strings)
  Regexp.new(strings.join("|"))
end

get_match(["Words", "word", "terrible", "one-way", "don't"])
get_match(["week", "month", "year"])

Match longest word before shorter

def get_match(strings)
  Regexp.new(strings.sort.reverse.join("|"))
end

get_match(["Yes", "Day", "Yesterday", "Daytime"])

Upvotes: 1

Related Questions