为什么||和/或在rails中表现不同?

时间:2010-10-11 09:15:09

标签: ruby-on-rails ruby

  

可能重复:
  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])

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

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

2 个答案:

答案 0 :(得分:8)

||的原因和/或表现不同是因为运算符优先。

两者都是||和&&优先级高于赋值运算符,赋值运算符(=)的优先级高于和/或

因此,您的表达式实际上将按如下方式进行评估: -

@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

如果对优先规则有疑问,请使用括号使您的意思清晰。

答案 1 :(得分:3)

引自http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators

  

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

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)

这就是区别。