i have a string variable which can only contain 6 different values. I want to check if it contains one of the first 4 values or one of the 2 second values.
我有一个字符串变量,只能包含6个不同的值。我想检查它是否包含前4个值之一或2个秒值之一。
Is there a more elegant way than this:
有没有比这更优雅的方式:
if string.eql? 'val1' || string.eql? 'val2' || string.eql? 'val3' || string.eql? 'val4'
...
elsif string.eql? 'val5' || string.eql? 'val6'
...
end
Maybe something like if string is in ['val1', 'val2', 'val3', 'val4']
?
也许像字符串在['val1','val2','val3','val4']中?
3 个解决方案
#1
15
You could use include?
:
你可以使用include?:
if ['val1', 'val2', 'val3', 'val4'].include?(string)
#2
1
case string
when *%w[val1 val2 val3 val4]
...
else
...
end
#3
0
数组索引#
Returns the index of the first object in ary such that the object is == to obj.Returns nil if no match is found.
返回ary中第一个对象的索引,使得对象为== to obj。如果未找到匹配则返回nil。
puts "something" if ['val1', 'val2', 'val3', 'val4'].index("val1")
# >> something
#1
15
You could use include?
:
你可以使用include?:
if ['val1', 'val2', 'val3', 'val4'].include?(string)
#2
1
case string
when *%w[val1 val2 val3 val4]
...
else
...
end
#3
0
数组索引#
Returns the index of the first object in ary such that the object is == to obj.Returns nil if no match is found.
返回ary中第一个对象的索引,使得对象为== to obj。如果未找到匹配则返回nil。
puts "something" if ['val1', 'val2', 'val3', 'val4'].index("val1")
# >> something