是否有更易读的方法来测试是否delivery_status
是三个字符串之一?
if ["partial", "successful", "unsuccessful"].include? delivery_status
这是我真正想要的,但它不起作用:
if delivery_status == ("partial" or "successful" or "unsuccessful")
是否有更易读的方法来测试是否delivery_status
是三个字符串之一?
if ["partial", "successful", "unsuccessful"].include? delivery_status
这是我真正想要的,但它不起作用:
if delivery_status == ("partial" or "successful" or "unsuccessful")
虽然我不建议这样做,但无论如何你都可以这样做:
def String
def is_one_of?(array)
array.include?(self)
end
end
接着:
if delivery_status.is_one_of?([...])
但是有一个更好的解决方案:用例(如果可能的话):
case delivery_status
when 'partial', 'successful', 'unsuccessful'
#stuff happens here
when ... #other conditions
end
It's not intuitive, but using the Regexp engine can speed these tests up:
STATES = ["partial", "successful", "unsuccessful"]
regex = /\b(?:#{ Regexp.union(STATES).source })\b/i
=> /\b(?:partial|successful|unsuccessful)\b/i
delivery_status = 'this is partial'
!!delivery_status[regex]
=> true
delivery_status = 'that was successful'
!!delivery_status[regex]
=> true
delivery_status = 'Yoda says, "unsuccessful that was not."'
!!delivery_status[regex]
=> true
delivery_status = 'foo bar'
!!delivery_status[regex]
=> false
If I'm not searching a string for the word, I'll use a hash for a lookup:
STATES = %w[partial successful unsuccessful].each_with_object({}) { |s, h| h[s] = true }
=> {"partial"=>true, "successful"=>true, "unsuccessful"=>true}
STATES['partial']
=> true
STATES['foo']
=> nil
Or use:
!!STATES['foo']
=> false
If you want a value besides true/nil/false:
STATES = %w[partial successful unsuccessful].each_with_index.with_object({}) { |(s, i), h| h[s] = i }
=> {"partial"=>0, "successful"=>1, "unsuccessful"=>2}
That'll give you 0
, 1
, 2
or nil
.
if %w[partial successful unsuccessful].include? delivery_status
我最终做了类似于@Linuxios 建议的事情
class String
def is_one_of(*these)
these.include? self
end
def is_not_one_of(*these)
these.include? self ? false : true
end
end
这让我可以写:
if delivery_status.is_one_of "partial", "successful", "unsuccessful"