Difference between "and" and && in Ruby?
and
is the same as &&
but with lower precedence. They both use short-circuit evaluation.
WARNING: and
even has lower precedence than =
so you'll usually want to avoid and
. An example when and
should be used can be found in the Rails Guide under "Avoiding Double Render Errors".
The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:
foo = :foobar = nila = foo and bar# => nila# => :fooa = foo && bar# => nila# => nila = (foo and bar)# => nila# => nil(a = foo) && bar# => nila# => :foo
The same thing works for ||
and or
.
The Ruby Style Guide says it better than I could:
Use &&/|| for boolean expressions, and/or for control flow. (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.)
# boolean expressionif some_condition && some_other_condition do_somethingend# control flowdocument.saved? or document.save!