Tuesday, July 6, 2010

Binding of or/and & ||/&&

Got bitten today by:
1
2
3
4
5
def call_1 ; false ; end
def call_2 ; true ; end

x = call_1 or call_2
# x => false

Because of binding issue of or, x is assigned to return of call_1 first, prior separated calling of call_2. Since what i actually want is to assign x to whichever valid (non nil/false) value of call_1 or call_2, i should use ||, which as a stronger binding, and code as:
1
2
x = call_1 || call_2
# x => true

The same applies for && & and.

No comments:

Post a Comment

Labels