开发者

Ruby: Is a string in a list of values

开发者 https://www.devze.com 2022-12-16 23:37 出处:网络
Newbie Ruby question: I\'m currently writing: if mystr开发者_开发百科ing == \"valueA\" or mystring == \"ValueB\" or mystring == \"ValueC\"

Newbie Ruby question:

I'm currently writing:

if mystr开发者_开发百科ing == "valueA" or mystring == "ValueB" or mystring == "ValueC"

is there a neater way of doing this?


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!


How 'bout

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消