Ruby: what is the difference between the comparatives: || and or
or the second example all variables are checked and if one is true then it will execute "do something".
This is false sentence.
As a result your assumptions are not correct.
Both or
and ||
do the same thing.
The main difference is that or
has lower precedence than ||
. So you should pay attention to more complex evaluations:
# Simple cases are not confusing
false || true # true
false or true # true
# This is more complex
a = false || true # a=true
a = false or true # a=false
# Also similarly as 1 + 2*3 returns 7, the following returns true:
false or false||true # true
# BUT! THIS IS IMPORTANT!
a = false or false||true # a=false
a = (false or false||true) # a=true
Here is a list of operators precedence.
So the real difference will be noticed if you use the expression that includes any of the following operators:
.. ...
- Range (inclusive and exclusive)? :
- Ternary if-then-else= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
- Assignmentdefined?
- Check if specified symbol definednot
- Logical negationand
- Logical composition
there might be others too.
You can thing about the difference between those as different between +
and *
: ||
==*
and or
=+
. The same applies to and
and not
.
You should really pay attention to that.
Personally I prefer ||
operator as its semantics is well understood and avoid or
.
While it 'feels' like or
is more friendly in many cases (see my code sample), even in trivial ones, it is a source of bugs.
Difference between or and || in Ruby?
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
Why || and or behaves differently in rails?
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.
Difference between or and || when setting variables
or
has lower precedence than =
.
test = nil or true
is the same as
(test = nil) or true
which is true
, while setting test
to nil
.
||
has higher precedence than =
.
test = nil || true
is the same as
test = (nil || true)
which is true
, while setting test
to true
.
Operator precedence for And/&& in Ruby
I don't quite understand the question you are asking. I mean, you have already given the answer yourself, before even asking the question: &&
binds tighter than =
while and
binds less tightly than =
.
So, in the first case, the expression is evaluated as follows:
( a=f(2) ) and ( b=f(4) )
( a= 2 ) and ( b=f(4) )
2 and ( b=f(4) ) # a=2
2 and ( b= 4 ) # a=2
2 and 4 # a=2; b=4
4 # a=2; b=4
In the second case, the evaluation is as follows:
a = ( f(2) && ( b=f(4) ) )
a = ( 2 && ( b=f(4) ) )
a = ( 2 && ( b= 4 ) )
a = ( 2 && 4 ) # b=4
a = 4 # b=4
4 # b=4; a=4
Why am I seeing different results for two expressions in Ruby, one uses '&&', other uses 'and' operator?
Because they have different operator precedence.
The first evaluates as:
(print (-1 == -1)) and (myobj.nil?)
It prints true, because -1 == -1, then print returns nil and nil and false
is nil.
The second is equivalent to:
print ((-1 == -1) && (myobj.nil?))
It prints (true && false), which is false, then print returns nil.
Is there any wisdom behind and, or operators in Ruby?
My guess is that's a direct carry-over from Perl. The operators or
and and
were added later in Perl 5 for specific situations were lower precedence was desired.
For example, in Perl, here we wish that ||
had lower precedence, so that we could write:
try to perform big long hairy complicated action || die ;
and be sure that the ||
was not going to gobble up part of the action. Perl 5 introduced or
, a new version of ||
that has low precedence, for exactly this purpose.
An example in Ruby where you could use or
but not ||
:
value = possibly_false or raise "foo"
If you used ||
, it would be a syntax error.
Using Kotlin WHEN clause for , =, =, comparisons
Even a flexible language such as Kotlin doesn't have a "elegant" / DRY solution for each and every case.
You can write something like:
when (foo) {
in 0 .. Int.MAX_VALUE -> doSomethingWhenPositive()
0 -> doSomethingWhenZero()
else -> doSomethingWhenNegative()
}
But then you depend on the variable type.
I believe the following form is the most idiomatic in Kotlin:
when {
foo > 0 -> doSomethingWhenPositive()
foo == 0 -> doSomethingWhenZero()
else -> doSomethingWhenNegative()
}
Yeah... there is some (minimal) code duplication.
Some languages (Ruby?!) tried to provide an uber-elegant form for any case - but there is a tradeoff: the language becomes more complex and more difficult for a programmer to know end-to-end.
My 2 cents...
Related Topics
Creating a Test Suite Using Ruby Minitest
Exception_Notification for Delayed_Job
Suppresing Output to Console with Ruby
Ruby - Does Array a Contain All Elements of Array B
Change Value of Request.Remote_Ip in Ruby on Rails
Devise Install from Existing Model/Database
Sort a List of Objects by Using Their Attributes in Ruby
How to Delete Some Folders of Nokogiri and Capybara-Webkit Inside of My Rvm Gemset
Ruby on Rails Activerecord Scopes VS Class Methods
Rvm Error While Running Make Install. Error Comes While Installing Power_Assert Gem
Converting an Array of Hashes to One Hash in Ruby
Ubuntu 12.10 - Ruby Gem Rmagick Missing Dependency Issue
Case Expression Different in Ruby 1.9
Configure Webrick to Use Automatically Generated Self-Signed Ssl/Https Certificate
How to Disable All Form_For Input Fields in Ruby on Rails App
Need Help Maximizing 3 Factors in Multiple, Similar Objects and Ordering Appropriately