Skip to content

Instantly share code, notes, and snippets.

@scottchiang
Created September 16, 2012 04:12
Show Gist options
  • Save scottchiang/3730968 to your computer and use it in GitHub Desktop.
Save scottchiang/3730968 to your computer and use it in GitHub Desktop.
Ternary Operators
=begin
I've seen ternary operators before but for some reason, I didn't appreciate it (or try to understand it) until now. Ternary operators can make if statements look a lot nicer (and shorter).
Here's an example:
=end
if x % 15 == 0
return "FizzBuzz"
else
return x
end
end
#This can be re-written as:
x % 15 == 0 ? "FizzBuzz" : x
=begin
There are some obvious advantages to using ternary operators. It's even possible to have nested ternary operators.
=end
x % 15 == 0 ? "FizzBuzz" : x % 5 == 0 ? "Buzz" : x.
=begin
The code isn't exactly the correct code for a fizzbuzz solution. I just used parts of it to illustrate my point. I'm starting to like ternary operators more and more now that I've actually sat down and understand it. I will definitely incorporate more ternary operators into my code from now on.
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment