Ruby 返回 bool 值的惯用方式

标签 ruby

#survey_completed? 中,是否有更惯用的方法返回 bool 值? 这就是我在 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

关于Ruby 返回 bool 值的惯用方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18272034/

相关文章:

ruby-on-rails - 我如何在 Rails 中测试 belongs_to 和 has_many?

ruby - 被调用的方法 `...'定义在这里

ruby - 使用 Ruby 将 HTML 转换为纯文本?

ruby - 为什么我的程序在提示用户之前接受用户输入?

ruby - 是否可以将命令行选项传递给 rspec 中的脚本

ruby - 使用 Ruby 和 Sinatra,是否可以以 "internal"或 "inline"方式使用 HAML?

ruby - 为什么用 Ruby 2.1 编写的代码必须能够被 Ruby 2.0 解释器解析?

ruby - 简化 `if then` block

ruby - 从 ruby​​ 获取到 capistrano 共享路径的路径

ruby-on-rails - 在 Rails 迁移中添加数据