为什么||和或在 Rails 中表现不同? [英] Why || and or behaves differently in rails?

查看:38
本文介绍了为什么||和或在 Rails 中表现不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
i = Ruby 中的真假为真?
Perl ( 或, and ) and ( ||, && ) 短路运算符?
Ruby:||之间的区别和'或'

|| 和 Rails 中的 or 一样吗?

Is || same as or in Rails?

案例 A:

 @year = params[:year] || Time.now.year
 Events.all(:conditions => ['year = ?', @year])

将在 script/console 中生成以下 SQL:

will produce the following SQL in script/console:

 SELECT * FROM `events` WHERE (year = 2000)

情况 B:

 @year = params[:year] or Time.now.year
 Events.all(:conditions => ['year = ?', @year])

将在 script/console 中生成以下 SQL:

will produce the following SQL in script/console:

 SELECT * FROM `events` WHERE (year = NULL)

推荐答案

原因 ||and or 行为不同是因为运算符优先级.

The reason that || and or behave differently is because of operator precedence.

两者||和&&具有比赋值运算符更高的优先级,并且赋值运算符 (=) 的优先级高于和/或

Both || and && have higher precedence than the assignment operator and the assignment operator (=) has higher precedence than and/or

所以你的表达式实际上将被评估如下:-

So your expressions will actually be evaluated as follows :-

@year = params[:year] ||时间.现在.年

被评估为

@year = ( params[:year] || Time.now.year )

@year = params[:year] 或 Time.now.year

被评估为

( @year = params[:year] ) 或 Time.now.year

如果对优先规则有疑问,请使用括号来表达您的意思.

If in doubt about precedence rules then use parentheses to make your meaning clear.

这篇关于为什么||和或在 Rails 中表现不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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