Skip to content

Instantly share code, notes, and snippets.

@mtheoryx
Created July 18, 2012 19:08
Show Gist options
  • Save mtheoryx/3138139 to your computer and use it in GitHub Desktop.
Save mtheoryx/3138139 to your computer and use it in GitHub Desktop.
Ruby short circuit "or"
# 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