6

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

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

2 Answers 2

17

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 .

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! very prettier and precise :)
4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.