Easiest Way to Display a Short If/Then/Else Statement

Ruby has many styles of handling conditional statements. You can use big, indented blocks of code if your program has complex statements. However, if you can say it all on one line, this often saves you time, and saves the time of people who may be reading your code later. It’s time to use the Ternary Operator.

We usually learn the longest method of conditional statements first. This is great when you are first learning, because it helps you get your thoughts out of your head and into the code. Here is an example:

if 1 + 2 == 3
"Yes, I did! ',=)"
else
"No, I didn't. =("
end
view raw ruby.rb hosted with ❤ by GitHub

That’s a pretty standard way of displaying an if/then/else block. Ruby doesn’t need a ‘then’ line of code, since it assumes that you want the first nested statement to run (I remember some old styles of programming that required more wordy code).

Here’s another way of expressing the exact same thing. It’s called the Ternary Operator. Notice the slight lack of clarity at first, but try to understand that Ruby is doing the exact same thing:

1 + 2 == 3 ? "Yes, I did! ',=)" : "No, I didn't. =("
view raw ruby.rb hosted with ❤ by GitHub

Take a look. First, we have just the conditional statement. No prefix is necessary. After the statement, place a ? with those spaces surrounding it. You can then follow it by your output if the conditional is true (the “then” of your block). Follow that with a : with more spaces surrounding that. You end it with your output if the conditional is false (the “else” of your block).

You don’t include if or else, or even an end. Ruby just knows what you mean. This can help you simplify nested conditional statements. If what you want returned is just a short string, or a variable, or another method, you can express that here.

Make sure you continue using the bigger blocks if what you need the computer to do is too hard to express in one line, though.

Easiest Way to Display a Short If/Then/Else Statement

Leave a comment