Skip to content

Instantly share code, notes, and snippets.

@domhnall
Last active November 7, 2022 22:04
Show Gist options
  • Save domhnall/268196b0bf0a89c902b15fb8e0e4a624 to your computer and use it in GitHub Desktop.
Save domhnall/268196b0bf0a89c902b15fb8e0e4a624 to your computer and use it in GitHub Desktop.
Short quiz to test how well you know operator precedence rules in ruby. See the [blog post](https://www.vector-logic.com/blog/posts/test-yourself-on-operator-precdence-in-ruby) to have a go at the quiz
# To test yourself on the actual quiz go to
# https://www.vector-logic.com/blog/posts/test-yourself-on-operator-precdence-in-ruby
a = false
b = true
c = 3
d = 4
expressions = [
"1 + 2 * 2", # Outputs 5
"4 * 6 / 2 * 2", # Outputs 24
"4 / 2 * 2 + 2 / 2", # Outputs 5
"4 * 2 ** 2 * 2", # Outputs 32
"5 + 10 % 3 + 6 / 2", # Outpus 9
"! a || b = false ; b", # Output true
"c or d == 7", # Outputs 3
"x = 5 && 4; x", # Outputs 4
"x = 5 and 4; x", # Outputs 5
"13 & 10 << 1", # Outputs 4
"a && b ? 'foo' : 'bar'", # Outputs 'bar'
"a and b ? 'foo' : 'bar'" # Outputs false
]
expressions.each_with_index do |expr, i|
puts "Question #{i}: #{expr}"
puts eval(expr)
puts "\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment