2

i've written a few lines of code like this :

if( (user_input.include?('string_a') || 
    (user_input.include? ('string_b')) || 
    (user_input.include?('string_c')) ) 
    && 
    user_input.include?('string_d_keyword'))
    ....
end # if

is there any function which can simplify the "multiple or string match" by taking multiple arguments and look like this ?

if( (user_input.multi_include_or?('string_a','string_b','string_c')) 
    && (user_input.include?('string_d_keyword')))
.....
end # if

i hope to do these all in a single line and so i've leave out the option of "case when".

Thanks~

1
  • I deleted my answer after seeing that I misread the question. I thought user_input was an array of strings. It's perfectly clear that it's a string. Commented Feb 22, 2017 at 7:28

2 Answers 2

5

You can do a regex match using | (or):

if user_input.match? /string_a|string_b|string_c|string_d_keyword/
  …
end

If your strings are in an array you can use Regexp.union to convert them to the corresponding regex:

if user_input.match? Regexp.union(strings)
  …
end
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply. BTW, i have to use this format to make it work : user_input.match( /string_a|string_b/ ) thx again~
Regex.union should be Regexp.union fyi.
1

Use an array and any?

> user_input = "string_a"
=> "string_a"
> ["asd","string_a"].any? {|a| user_input.include? a}
=> true

1 Comment

What's with the downvote? Is there something wrong with this solution?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.