0

是否有更易读的方法来测试是否delivery_status是三个字符串之一?

if ["partial", "successful", "unsuccessful"].include? delivery_status

这是我真正想要的,但它不起作用:

if delivery_status == ("partial" or "successful" or "unsuccessful")
4

4 回答 4

3

虽然我建议这样做,但无论如何你都可以这样做:

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
于 2013-06-10T15:59:23.250 回答
1

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.

于 2013-06-10T17:08:23.427 回答
1
if %w[partial successful unsuccessful].include? delivery_status
于 2013-06-10T16:01:07.953 回答
0

我最终做了类似于@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"
于 2013-06-10T16:15:26.557 回答