Ruby 运算符 - 公式

Ruby operators - formula

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

我在首选项 table 中有一个属性,称为延迟。我想计算一个用户的容忍度是否接近另一个用户要求的延迟。

在我的 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...
..

问题是 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 你就没有默认情况,所以如果这三个条件中的 none 是 true,你应该考虑你想要什么行为。

P.S。您可以通过将这些值分配给名称较短的局部变量来使它 lot 更具可读性:

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

P.P.S。 0.90.5magic numbers。考虑将它们的值移动到常量中。

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