The operator || (OR) will return whatever value that is truthy first
Eg:
"abc" || "cde"
# return "abc" because it is truthy , and it return 'abc' without verifying 'cde'.
The operator && (AND) will return whatever value that is 'false' or 'nil' first
Eg:
nil && false
# return nil
false && nil
# return false
'abc' && 'cde'
# return 'cde' because 'abc' is truthy.
So the short-hand
name ||= 'default'
is equal to
name = name || 'default'
meaning that is name is not false or nil, then it is assigned back to name.
eg : if name is already 'John' then name = 'John'.
if name is false or nil, then || operator will evaluate the second part of OR operator, and return 'default' because it is truthy.
Eg:
"abc" || "cde"
# return "abc" because it is truthy , and it return 'abc' without verifying 'cde'.
The operator && (AND) will return whatever value that is 'false' or 'nil' first
Eg:
nil && false
# return nil
false && nil
# return false
'abc' && 'cde'
# return 'cde' because 'abc' is truthy.
So the short-hand
name ||= 'default'
is equal to
name = name || 'default'
meaning that is name is not false or nil, then it is assigned back to name.
eg : if name is already 'John' then name = 'John'.
if name is false or nil, then || operator will evaluate the second part of OR operator, and return 'default' because it is truthy.
Comments
Post a Comment