Ruby:是值列表中的字符串

时间:2022-03-04 22:52:33

Newbie Ruby question:

新手Ruby问题:

I'm currently writing:

我现在正在写:

if mystring == "valueA" or mystring == "ValueB" or mystring == "ValueC"

is there a neater way of doing this?

这样做有一个更简洁的方法吗?

3 个解决方案

#1


35  

There are two ways:

有两种方法:

RegEx:

正则表达式:

if mystring =~ /^value(A|B|C)$/ # Use /\Avalue(A|B|C)\Z/ here instead 
   # do something               # to escape new lines
end

Or, more explicitly,

或者,更明确地说,

if ["valueA", "valueB", "valueC"].include?(mystring)
   # do something
end

Hope that helps!

希望有所帮助!

#2


5  

How 'bout

怎么样

if %w(valueA valueB valueC).include?(mystring)
  # do something
end

#3


1  

Presuming you'd want to extend this functionality with other match groups, you could also use case:

假设您想要将此功能扩展到其他匹配组,您还可以使用大小写:

case mystring
when "valueA", "valueB", "valueC" then
 #do_something
when "value1", "value2", "value3" then
 #do_something else
else
 #do_a_third_thing
end

#1


35  

There are two ways:

有两种方法:

RegEx:

正则表达式:

if mystring =~ /^value(A|B|C)$/ # Use /\Avalue(A|B|C)\Z/ here instead 
   # do something               # to escape new lines
end

Or, more explicitly,

或者,更明确地说,

if ["valueA", "valueB", "valueC"].include?(mystring)
   # do something
end

Hope that helps!

希望有所帮助!

#2


5  

How 'bout

怎么样

if %w(valueA valueB valueC).include?(mystring)
  # do something
end

#3


1  

Presuming you'd want to extend this functionality with other match groups, you could also use case:

假设您想要将此功能扩展到其他匹配组,您还可以使用大小写:

case mystring
when "valueA", "valueB", "valueC" then
 #do_something
when "value1", "value2", "value3" then
 #do_something else
else
 #do_a_third_thing
end