Ruby三元运算符和方法调用 [英] Ruby ternary operator and method call

查看:142
本文介绍了Ruby三元运算符和方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ruby 2.1.5,三元运算符遇到了一些问题

I am using ruby 2.1.5, facing some problem with ternary operator

语法错误

request.xhr?  ? render :json => "success"  : redirect_to index_url

工作

request.xhr?  ? render(:json => "success") : redirect_to(index_url)

能否请您解释一下它是如何工作的,以及为什么上面的一个不起作用?预先感谢

Can some please explain How its works and why above one not working? Thanks in advance

推荐答案

使用简写语法(不带方括号)时,ruby期望直到行尾的所有内容都是方法的参数.因此,您的语法错误"示例应理解为:

When you use the shorthand syntax (without brackets), ruby expects everything until the end of the line to be parameters to your method. So your "syntax error" example is understood as:

request.xhr?  ? render(:json => "success"  : redirect_to index_url)

这显然是错误的.

这篇关于Ruby三元运算符和方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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