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)
这显然是错误的.