Reputation: 87
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
Reputation: 23849
Well, you could always use a regular expression here (risking another jwz quote :)
if mystring =~ /string1|string2|string3/
...
end
Upvotes: 4
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 notfalse
ornil
.
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