为什么三元运算符不能与重定向一起使用

编程入门 行业动态 更新时间:2024-10-28 12:18:01
本文介绍了为什么三元运算符不能与重定向一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我喜欢三元运算符.它确实清理了代码外观,但我有一个案例,它在 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}))

更多推荐

为什么三元运算符不能与重定向一起使用

本文发布于:2023-11-01 23:45:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550747.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能与   运算符   重定向

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!