한승우
한승우

Reputation: 25

How to check if a string includes any value of an array?

My string is

str = "my string is this one"

and my array is

arr = ["no", "nothing", "only", "is"]

So, my string includes the is in the value of my array, I want to get the result true

How can I do this?

I want to use include? met

Upvotes: 1

Views: 401

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

(str.downcase.split & arr.map(&:downcase)).any?
   #=> false

If it is known that all letters are of the same case.

(str.split & arr).any?
   #=> false

Upvotes: 1

steenslag
steenslag

Reputation: 80065

This uses a Regular expression. The good news is that it is generated for you - no syntax to learn. Other good news: it traverses the string only once.

re = Regexp.union(arr)  #your own regular expression without screws or bolts
p re.match?(str)  # => true

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

To check when the whole word is included case sensitive:

(str.split & arr).any?
#⇒ true

Case insensitive:

[str.split, arr].map { |a| a.map(&:downcase) }.reduce(&:&).any?
#⇒ true

To check if it includes any of arr anyhow:

arr.any?(&str.method(:include?))
#⇒ true

Upvotes: 3

Related Questions