Ruby返回布尔值的惯用方法

4

#survey_completed?方法中,是否有更符合惯用语的方式来返回一个布尔值?这是我在C#中的做法,我一直觉得最后的三元条件运算符返回false是多余的,也许Ruby有更好的方法来实现这个功能呢?

以下是我的代码:

  def survey_completed?
    self.survey_completed_at ? true: false
  end

  def survey_completed_at
    # Seeing as the survey is submitted all or nothing, the time the last response is persisted
    # is when the survey is completed
    last_response = self.responses.last
    if last_response
      last_response.created_at
    end
  end
3个回答

7
您可以使用双重否定:
def survey_completed?
  !!survey_completed_at
end

一般情况下,如果您的输入是字符串,请小心使用 !!,因为它会对空字符串返回 true,这可能不是期望的行为。只是提供信息。 - Iuri G.
在这种情况下,activesupport库中的 Object#present? 很有用。 - Marek Lipka
1
@MarekLipka Object#present? 是Rails的扩展。假设您正在使用Rails核心扩展,那么是的,Object#present? 更好。 - Iuri G.
@IuriG,是的,我甚至写下了这个方法来自 activesupport。 - Marek Lipka

2
  def survey_completed?
    !survey_completed_at.nil?
  end

2
如果 survey_completed_atfalse,则此代码将返回 true,这可能是预期的,也可能不是。 - Andrew Marshall
1
survey_completed_at 是一个日期时间字段。 - Lee

1
在Ruby中,惯用的做法是不要这样做。除了falsenil外,每个对象在布尔上下文中都会被评估为true。因此,您的survey_completed_at函数已经实现了survey_completed?函数的目的。
如果您收到了调查回复,last_response.created_at将是非空的,因此该函数将在布尔上下文中评估为true。如果您没有收到回复,并且last_responsenil,则if将评估为nil,并且该函数将在布尔上下文中评估为false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接