为什么三元运算符不能与重定向一起使用 [英] Why won't ternary operator work with redirect

查看:22
本文介绍了为什么三元运算符不能与重定向一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢三元运算符.它确实清理了代码外观,但我有一个案例,它在 Rails 控制器中无法正常运行.

I love the ternary operator. It really cleans up the code look, but I have a case where it won't behave correctly in a Rails controller.

我收到一个语法错误:unexpected tSYMBEG,expecting keyword_do or '{' or '('

我一直遇到这个问题,它点亮了将下面的语句更改为三元运算符的开关.当我尝试将它与重定向语句结合使用时,它总是会发生.

I consistently get this issue, it light switches on changing the statement below to a ternary operator. It always happens when I'm trying to use it in conjunction with a redirect statement.

我是否不知道有关此的规则?

Am I unaware of a rule about this?

if nexti==0 then
  redirect_to :back
else
  redirect_to edit_playt_path(id: actform['playt_id'], i: nexti)
end

nexti==0 ? redirect_to :back : redirect_to edit_playt_path(id: actform['playt_id'], i: nexti)

推荐答案

因为散列的隐含性质

Ruby/Rails 将暗示您重定向的参数是一个哈希值,这在您的示例中具有一些尴尬的含义

Ruby / Rails will imply your argument to redirect is a hash which has some awkward implications in your example

当 ruby​​ 暗示要重定向的参数时,它在以下场景中将其视为散列,它将其解析为

When ruby implies the arguments to redirect it sees it as a hash in the following scenario it is parsing it as

nexti==0 ? redirect_to({:back, : redirect_to edit_playt_path(id: actform['playt_id'], i: nexti})

这是无效的,如果您明确定义哈希/参数,它应该可以工作

which is invalid, it should work if you explicitly define your hash / argument

nexti==0 ? redirect_to(:back) : redirect_to(edit_playt_path({id: actform['playt_id'], i: nexti}))

大多数 ruby​​/rails 开发人员会出于此类原因告诉您避免使用三元组,以及人类对正在发生的事情的一般理解.Ruby 被认为是一种富有表现力的语言,所以拥抱它吧.

most ruby / rails devs will tell you to avoid ternaries for reasons like this, and also general human comprehension of what is going on. Ruby was ment to be an expressive language, so embrace it.

return redirect_to(:back) if nexti==0
redirect_to(edit_playt_path({id: actform['playt_id'], i: nexti}))

这篇关于为什么三元运算符不能与重定向一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆