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~

jimzcc
  • 142
  • 4
  • 13
  • 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. – Cary Swoveland Feb 22 '17 at 07:28

2 Answers2

4

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
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
1

Use an array and any?

> user_input = "string_a"
=> "string_a"
> ["asd","string_a"].any? {|a| user_input.include? a}
=> true
Coolness
  • 1,932
  • 13
  • 25