【问题标题】:Ruby operators - formulaRuby 运算符 - 公式
【发布时间】:2016-06-27 11:02:36
【问题描述】:

我正在尝试在我的 rails 4 应用程序中的 project.rb 模型中创建一个公式。

我在偏好表中有一个属性,称为延迟。我想计算一个用户的容差是否接近另一个用户所需的延迟。

在我的 project.rb 中,我尝试按如下方式执行此操作:

def publication_delay_variance
    if @current_user.profile.organisation.preference.delay >=  @project.profile.organisation.preference.delay
      'No problems here'
    elsif @current_user.profile.organisation.preference.delay * 90% >= @project.profile.organisation.preference.delay
      "Close, but not quite there"
    else   @current_user.profile.organisation.preference.delay * 50% >=  @project.profile.organisation.preference.delay

      "We're not in alignment here"
    end
  end

当前用户是当前登录并与页面交互的当前用户。另一个用户是创建项目的用户。每个用户都有一个组织。每个组织都有偏好。我正在尝试比较它们。

谁能看到我做错了什么?我对此没有太多经验。我当前的尝试产生了这个错误:

syntax error, unexpected >=
...ence.publication_delay * 90% >= @project.profile.organisatio...
..

【问题讨论】:

    标签: ruby-on-rails ruby operators formula


    【解决方案1】:

    问题是90% 在 Ruby 中无效。您可能打算改用0.9。另外,您最后的else 应该是elsif

    def publication_delay_variance
      if @current_user.profile.organisation.preference.delay >= @project.profile.organisation.preference.delay
        'No problems here'
      elsif @current_user.profile.organisation.preference.delay * 0.9 >= @project.profile.organisation.preference.delay
        "Close, but not quite there"
      elsif @current_user.profile.organisation.preference.delay * 0.5 >= @project.profile.organisation.preference.delay
        "We're not in alignment here"
      end
    end
    

    当然,如果没有else,你就没有默认情况,所以你应该考虑如果这三个条件都不是true,你想要什么行为。

    附:您可以通过将这些值分配给具有较短名称的局部变量来使其很多更具可读性:

    def publication_delay_variance
      user_delay = @current_user.profile.organisation.preference.delay
      project_delay = @project.profile.organisation.preference.delay
    
      if user_delay >= project_delay
        "No problems here"
      elsif user_delay * 0.9 >= project_delay
        "Close, but not quite there"
      elsif user_delay * 0.5 >= project_delay
        "We're not in alignment here"
      end
    end
    

    附言0.90.5magic numbers。考虑将它们的值移动到常量中。

    【讨论】:

    • 非常感谢。我刚刚意识到我不能在我的项目模型中使用 current_user 。回去想办法解决这个问题,然后我会回来试一试。
    • 如果这是 User 模型上的一个实例方法,那么你可以让它接受一个 Project 作为参数,这样你就可以从你的控制器或视图中调用它,例如 @current_user.publication_delay_variance(@project)
    • 我在我的项目模型中的一个方法中得到了它。
    • 哦,那么你可以反过来做,将用户作为参数,例如@project.publication_delay_variance(@current_user).
    • 谢谢。我必须学习如何使用它。我尝试将该行复制到我的项目显示操作中(然后在 project.rb 方法中引用@current_user,'current_user' - 但这是不正确的。我将尝试学习如何使用它并尝试一下。再次感谢
    【解决方案2】:

    在 Ruby 中,% 是取模运算符,它接受两个参数 x % y 并返回 x / y 的余数。 >= 紧随其后没有意义,这就是错误消息告诉您的内容。要在 Ruby 中表示百分比,请使用十进制数,例如 0.9。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 2012-08-04
      • 2013-07-04
      • 2012-01-24
      • 2012-09-15
      • 2011-07-12
      相关资源
      最近更新 更多