2010-07-07 67 views

回答

9

最常見的解決方案是使用Array#include?

do_something if %w(first second third).include? my_string 
+0

Awww,我一直在尋找形式my_string.in%w(第一個第二個第三)的方法。我只需要扭轉我的觀點:)謝謝。 – hundredwatt 2010-07-07 20:20:48

+0

你真的可以選擇Enumerable方法,detect是Enumerable#detect是另一個不錯的方法http://apidock.com/ruby/Enumerable/detect但是它返回nil,如果沒有找到值則返回false – 2010-07-07 20:21:09

0
do_something() if ['first', 'second', 'third'].include? my_string 
0

do_something if my_string =~ /^(first|second|third)$/

0

如果擔心效率和/或易讀性,我建議你首先構建特殊值的一個列表一個很好的常數名稱,解釋爲什麼這些是特殊的,然後使用它:

require 'set' 
SPECIAL_VALUES = Set["first", "second", "third"] 

def foo(my_string) 
    do_something if SPECIAL_VALUES.include?(my_string) 
end 

如果您想處理「第一」,「第二」等情況的方式有所不同,那麼您可以使用Hash而不是Set

相關問題