Test if variable matches any of several strings w/o long if-elsif chain, or case-when
12,222
Solution 1
Perhaps you didn't know that you can put multiple conditions on a single case:
case mystr
when "abc", "def", "ghi", "xyz"
..
end
But for this specific string-based test, I would use regex:
if mystr =~ /\A(?:abc|def|ghi|xyz)\z/
If you don't want to construct a regex, and you don't want a case
statement, you can create an array of objects and use Array#include?
test to see if the object is in the array:
if [a,b,c,d].include?( o )
or, by monkey-patching Object, you can even turn it around:
class Object
def in?( *values )
values.include?( self )
end
end
if o.in?( a, b, c, d )
Solution 2
You can use Array#include?
like this:
if ["abc", "def ", "ghi", "xyz"].include?(mystr)
Solution 3
>> mystr="abc"
=> "abc"
>> mystr[/\A(abc|def|ghi|xyz)\z/]
=> "abc"
>> mystr="abcd"
=> "abcd"
>> mystr[/\A(abc|def|ghi|xyz)\z/]
=> nil
Author by
jpw
Updated on June 20, 2022Comments
-
jpw almost 2 years
I assume there is a nice one-line way to say in ruby
if mystr == "abc" or "def " or "ghi" or "xyz"
but cannot find how to do that in the online references I normally consult...
Thanks!
-
Jörg W Mittag over 13 yearsAnd in this specific case, I would use the whitespace delimited array literal syntax to get rid of all the commas and quotes:
%w[abc def ghi xyz].include?(mystr)
-
jpw about 13 yearswhat dos the ?: do? (google doesnt let you search for symbols, and the three ruby/regex guides I looked up didnt have : far as I can tell)
-
Phrogz about 13 yearsIn a regex you use parentheses to limit an expression and also to capture it for later use. In this case we don't actually need to or want to capture it, so putting
?:
at the start of the parentheses is an instruction not to capture it. See the official Oniguruma regex syntax for more information. -
jpw over 11 yearsbecause I completely missed the 3rd example you provided, which was the same as the (excellent/succinct) provided by sepp2k. Fixed. It is cool you provided several examples, thx.