如何绕过 Only use the parentheses for ternary expressions with complex conditions?

How do I bypass Only use parentheses for ternary expressions with complex conditions?

我的代码如下所示:

def redirector
  # :nocov:
  unless ENV["URL"]
    return "https://google.com"
  end
  # :nocov:

  redirect_url = (request.original_fullpath.include? "404") ? root_path : request.original_url
  param_object = { redirect: redirect_url }

  ENV["URL"] + "?" + param_object.to_param
end

有没有更好的写法?

redirect_url = (request.original_fullpath.include? "404") ? root_path : request.original_url

你可以这样写:

redirect_url = request.original_fullpath.include?("404") ? root_path : request.original_url

甚至:

redirect_url = if request.original_fullpath.include? "404"
  root_path
else
  request.original_url
end

您收到有关括号的警告,因为您的条件很简单。复杂条件如下所示:

foo = (bar && baz) ? a : b

Check out the doc.