Ruby Check condition if a string include multi-different strings?
ruby, ruby-on-rails
Solution
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` .
Problem
I am newbie to Ruby. Are there any better ways to write this: ``` if (mystring.include? "string1") || (mystring.include? "string2") || (mystring.include? "string3") ```