2010-10-11 26 views
2

可能重复:
i = true and false in Ruby is true?
What is the difference between Perl's (or, and) and (||, &&) short-circuit operators?
Ruby: difference between || and 'or'为什么||和或在轨道中表现不同?

||相同的Rails or

例A:

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

将产生script/console以下SQL:

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

情况B:

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

将产生以下SQL中script/console

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

同样的问题[我=真和假的Ruby是真实的?](http://stackoverflow.com/questions/2802494/i-true-and-false-in-ruby-is-true)除了'或'而不是'和'。 – sepp2k 2010-10-11 09:17:17

+2

复制到:http://stackoverflow.com/questions/3826112/in-ruby-should-we-always-use-instead-of-and-or-unless-for-specia/3828955#3828955,http:// stackoverflow.com/questions/1512547/what-is-the-difference-between-perls-or-and-and-short-circuit-op可能还有更多。 – draegtun 2010-10-11 10:08:48

+3

此问题已在http://StackOverflow.Com/q/2083112/,http://StackOverflow.Com/q/1625946/,http://StackOverflow.Com/q/1426826/,http ://StackOverflow.Com/q/1840488/,http://StackOverflow.Com/q/1434842/,http://StackOverflow.Com/q/2376369/,http://StackOverflow.Com/q/2802494/ ,http://StackOverflow.Com/q/372652/。 – 2010-10-11 13:26:16

回答

7

||的原因。和/或行为不同是因为运营商的优先权。

双方||和& &比赋值运算符和赋值运算符(=)的优先级高的优先级高于和/或

所以,你的表情实际上将评价如下: -

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

评估作为

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

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

作为

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

如有疑问评估有关优先规则,然后使用括号,让您的意思很清楚。

3

报价:

二进制“或”运算符将返回它的两个操作数的逻辑和。它与“||”相同但优先级较低。

a = nil 
b = "foo" 
c = a || b # c is set to "foo" its the same as saying c = (a || b) 
c = a or b # c is set to nil its the same as saying (c = a) || b which is not what you want. 

所以你or作品:

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

所以params[:year]被分配到@year,和表达的第二部分没有分配到任何东西。如果要使用或者,应该使用明确的括号:

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

这是区别。

相关问题