2013-08-16 209 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