[英]What is the Ruby idiomatic way to merge two hashes of boolean values over boolean operations?
[英]Ruby idiomatic way to return a boolean
有没有更惯用的方式让我在#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
您可以使用双重否定:
def survey_completed?
!!survey_completed_at
end
def survey_completed?
!survey_completed_at.nil?
end
在 Ruby 中执行此操作的惯用方法是不执行此操作。 在布尔上下文中,除了false
和nil
之外的每个对象都计算为true
。 因此,您的survey_completed_at
函数已经达到了survey_completed?
功能。
如果您收到调查回复, last_response.created_at
将不是 nil,因此该函数将在布尔上下文中评估为true
。 如果您没有得到响应并且last_response
为nil
,则 if 将评估为nil
并且该函数将在布尔上下文中评估为false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.