tags:

views:

495

answers:

2

What is the difference between && and and operators in Ruby?

+15  A: 

and is the same as && but with lower precedence. They both use short-circuit evaluation.

Dominic Rodger
+6  A: 

The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo

The same thing works for || and or.

tadman
+1 - fantastic examples!
Dominic Rodger