Created
September 16, 2012 04:12
-
-
Save scottchiang/3730968 to your computer and use it in GitHub Desktop.
Ternary Operators
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
=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