2010-10-11 25 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) 

這是區別。

相關問題