Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created November 7, 2017 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/fb3182692bb5a9e8922b62512fdd22d7 to your computer and use it in GitHub Desktop.
Save JoshCheek/fb3182692bb5a9e8922b62512fdd22d7 to your computer and use it in GitHub Desktop.
Ruby && is control flow
# Note that we can use parentheses to group expressions together,
# we'll use this to make a "side-effect" of incrementing a number,
# and then return a boolean value (true / false)
i = 0
(i += 1; true) # => true
(i += 1; false) # => false
i # => 2
# Lets look at the short-circuiting of &&
# When the left-hand side is true, it evaluates the right hand side
i = 0 # => 0
(i += 1; true) && (i += 1; true) # => true
i # => 2
(i += 1; true) && (i += 1; false) # => false
i # => 4
# When the left-hand side is false, it doesn't need to check the right-hand side
i = 0 # => 0
(i += 1; false) && (i += 1; true) # => false
i # => 1
(i += 1; false) && (i += 1; false) # => false
i # => 2
# Note that this is very different from how things like methods work, if it was
# a method, it would evaluate its arguments before being called, so it would
# always have the side-effect of incrementing our number!
def my_and(left, right)
left && right
end
i = 0 # => 0
my_and((i += 1; false), (i += 1; true)) # => false
i # => 2
my_and((i += 1; false), (i += 1; false)) # => false
i # => 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment