Created
July 18, 2012 19:08
-
-
Save mtheoryx/3138139 to your computer and use it in GitHub Desktop.
Ruby short circuit "or"
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
| # First, let's explain some "normal" conditional OR behavior. | |
| # I'm going to use some IRB output here because IRB always prints | |
| # an evaluation value to the screen; this will help. | |
| # Just setting up some variables to play with | |
| # The comment that starts with "#=>" is the result | |
| # of the operation, and IRB prints this out for us | |
| # automatically | |
| 1.9.3p194 :001 > a = 1 | |
| #=> 1 | |
| 1.9.3p194 :002 > b = 2 | |
| #=> 2 | |
| # Here, you can see the expected output of 1 | |
| # That's because a was evaluated first | |
| # But notice that IRB printed a 2, not nil (return value of puts method). | |
| # That's becaue b, which equals 2, was the last | |
| # thing evaluated, and therefore is what IRB prints out to us. | |
| # It is proof that b was in fact evaluated | |
| 1.9.3p194 :003 > puts a or b | |
| 1 | |
| #=> 2 | |
| # Now, using short circuit evaluation instead. | |
| # We can see that we still get the logical result from a | |
| # But b is never even evaluated, thus IRB | |
| # simply printed the value of evaluating, essentially | |
| # the statement "puts a", which produces the default | |
| # return value from puts, which is nil. | |
| 1.9.3p194 :004 > puts a || b | |
| 1 | |
| #=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment