Last active
August 29, 2015 14:11
-
-
Save aghyad/59d556c8fcf8467456ba to your computer and use it in GitHub Desktop.
"&&" and "||" in ruby statements (not if-stmts)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"&&" and "||" in ruby statements (not if-stmts): | |
stmt1 && stmt2 | |
returns the first falsey result, or if no falsey's found, returns the last truthy result | |
ex: | |
'hello' && 'bye' | |
=> 'bye' | |
'hello' && false | |
=> false | |
false && 'hello' | |
=> false | |
nil && false && 'hello' | |
=> nil | |
'hello' && false && nil && 'bye' | |
=> false | |
======================================================================= | |
stmt1 || stmt2 | |
returns the first truthy result, or if no truthy's found, returns the last falsey result | |
ex: | |
'hello' || 'bye' | |
=> 'hello' | |
'hello' || false | |
=> 'hello' | |
false || 'hello' | |
=> 'hello' | |
nil || false || 'hello' | |
=> 'hello' | |
false || nil | |
=> nil | |
nil || false | |
=> false | |
======================================================================= | |
In summary, if falsey's break &&, and if truthy's break ||: | |
If breakers found, stop there, and return the result at that point. | |
If NO breakers found, continue executing until the end, and then return the last result. | |
So, how's this useful? | |
Well, we can use a chaining of && and || to rewrite some if-stmts, for example: | |
if x > 5 | |
puts "greater" | |
else | |
puts "smaller" | |
end | |
You can rewrite this as: | |
puts x>5 && "greater" || "smaller" | |
Done! easy breezy short form. | |
Mind blowing, huh? | |
A word of caution here is to pay attention when mixing &&'s and ||'s to use parantheses to make sure precedence is evaluated correctly. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment