2013-08-16 149 views
3

Ruby的惯用方式是有我返回在#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 

回答

5

你可以用双重否定:

def survey_completed? 
    !!survey_completed_at 
end 
+0

这正是我一般需要寻找的 – Lee

+0

,如果你的输入是字符串,请小心'!!',因为它会返回空白字符串的真值,这可能不是期望的行为。只是FYI –

+0

@IuriG。在这种情况下,activesupport'Object#present?'很有用。 –

2
def survey_completed? 
    !survey_completed_at.nil? 
    end 
+1

你不需要'self',所以我编辑了.. :) * + 1 * ... –

+2

如果'survey_completed_at'是'false',这可能会返回'true',这可能会或可能不会。 –

+1

survey_completed_at是日期时间字段 – Lee

0

惯用的方式做到这在Ruby中是不做。除了falsenil以外的每个对象在布尔上下文中评估为true。因此你的survey_completed_at函数已经服务于survey_completed?函数的目的。

如果您得到了调查回复,last_response.created_at将是非零,因此该函数将在布尔上下文中计算为true。如果您没有得到响应,并且last_responsenil,则if将评估为nil,并且该函数将在布尔上下文中评估为false