Hedge
Hedge

Reputation: 16766

Check whether a string contains one of multiple substrings

I've got a long string-variable and want to find out whether it contains one of two substrings.

e.g.

haystack = 'this one is pretty long'
needle1 = 'whatever'
needle2 = 'pretty'

Now I'd need a disjunction like this which doesn't work in Ruby though:

if haystack.include? needle1 || haystack.include? needle2
    puts "needle found within haystack"
end

Upvotes: 62

Views: 77340

Answers (8)

folium
folium

Reputation: 413

Use or instead of ||

if haystack.include? needle1 or haystack.include? needle2

or has lower presedence than || , or is "less sticky" if you will :-)

Upvotes: 0

Seph Cordovano
Seph Cordovano

Reputation: 2054

For an array of substrings to search for I'd recommend

needles = ["whatever", "pretty"]

if haystack.match?(Regexp.union(needles))
  ...
end

Upvotes: 9

flogram_dev
flogram_dev

Reputation: 42888

You can do a regex match:

haystack.match? /needle1|needle2/

Or if your needles are in an array:

haystack.match? Regexp.union(needles)

(For Ruby < 2.4, use .match without question mark.)

Upvotes: 25

Kapitula Alexey
Kapitula Alexey

Reputation: 388

To check if contains at least one of two substrings:

haystack[/whatever|pretty/]

Returns first result found

Upvotes: 6

Shiko
Shiko

Reputation: 2624

I was trying to find simple way to search multiple substrings in an array and end up with below which answers the question as well. I've added the answer as I know many geeks consider other answers and not the accepted one only.

haystack.select { |str| str.include?(needle1) || str.include?(needle2) }

and if searching partially:

haystack.select { |str| str.include?('wat') || str.include?('pre') }

Upvotes: 0

rgtk
rgtk

Reputation: 3510

(haystack.split & [needle1, needle2]).any?

To use comma as separator: split(',')

Upvotes: 10

seph
seph

Reputation: 6076

[needle1, needle2].any? { |needle| haystack.include? needle }

Upvotes: 105

danh
danh

Reputation: 62686

Try parens in the expression:

 haystack.include?(needle1) || haystack.include?(needle2)

Upvotes: 69

Related Questions