Kuroun
Kuroun

Reputation: 87

Ruby Check condition if a string include multi-different strings?

I am newbie to Ruby. Are there any better ways to write this:

if (mystring.include? "string1") || (mystring.include? "string2") ||
   (mystring.include? "string3")

Upvotes: 6

Views: 5107

Answers (2)

nimrodm
nimrodm

Reputation: 23849

Well, you could always use a regular expression here (risking another jwz quote :)

if mystring =~ /string1|string2|string3/
  ...
end

Upvotes: 4

Arup Rakshit
Arup Rakshit

Reputation: 118299

Yes, as below :

if %w(string1 string2 string3).any? { |s| my_string.include? s }
  # your code
end

Here is the documentation : Enumerable#any?

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil.

Here is another way ( more fastest) :

[13] pry(main)> ary = %w(string1 string2 string3)
=> ["string1", "string2", "string3"]
[14] pry(main)> Regexp.union(ary)
=> /string1|string2|string3/
[15] pry(main)> "abbcstring2"[Regexp.union(ary)]
=> "string2"
[16] pry(main)> "abbcstring"[Regexp.union(ary)]
=> nil

Just read Regexp::union and str[regexp] → new_str or nil .

Upvotes: 17

Related Questions