Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why || and or behaves differently in rails? [duplicate]

Possible Duplicates:
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'

Is || same as or in Rails?

Case A:

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

will produce the following SQL in script/console:

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

Case B:

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

will produce the following SQL in script/console:

 SELECT * FROM `events` WHERE (year = NULL)
like image 976
ohho Avatar asked Dec 03 '22 11:12

ohho


1 Answers

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] || Time.now.year

is evaluated as

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

and

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

is evaluated as

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

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

like image 102
Steve Weet Avatar answered Dec 22 '22 07:12

Steve Weet