什么是更可读的方法来测试三个字符串之一?

时间:2013-06-10 15:55:24

标签: ruby code-readability

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

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

这是我真正喜欢的,但它不起作用:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

if %w[partial successful unsuccessful].include? delivery_status

答案 2 :(得分:1)

这不直观,但使用Regexp引擎可以加快这些测试的速度:

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

如果我没有在字符串中搜索单词,我将使用哈希进行查找:

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

或使用:

!!STATES['foo']
=> false

如果你想要一个除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}

这会给你012nil

答案 3 :(得分: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"