Shorthand style!

This being week 6 or so into my coding life, I’ve done a handful of if then statements. Each statements are quite simple, if “this”, do “this” else do “that”. Consider the following code:
``` 
if your_name == ‘mark’
 puts “You are amazing!”
 end
```
The above code is pretty straight forward:
first line compares “your_name” to “mark”, if that returns to be true, the terminal will print out “you are amazing!”, and lastly it will end the operation with ‘end’.

I use 3 lines of code to do something quite simple, but what if I were to say this can be done in one line?!? Imagine how much more “dry” your code will be! How do you do this? It is called shorthand! Look carefully at the below code:
```
puts "You are amazing!" if your_name == mark
```

Yes that’s right folks, an if then statement can be executed in one line! I know what you’re thinking, someone should have taught you this at the beginning of your coding career, how much less code will be written! On one hand, that is very true, however the traditional if-then statements are easier to read and makes more sense for rookie coders. Once when you master the traditional concept, then the one liner will make more sense. Now, I know what you’re all thinking, is it possible to write an if-then-else statement on one line? Well, let’s see this in our traditional if-then-else:
```
if your_name == ‘mark’
 puts “You are amazing!”
else
puts “You’re not as amazing as mark.”
end
```
Now, we know how to do the one liner without the else, whats the syntax needed for the else? I’ll show the one liner to amaze you first, then will explain the code:

your_name == mark ? (puts "You are amazing!") : (puts "You're not as amazing as mark.")

The first part of the code: your_name == mark? is line 1 in the traditional code, if your_name == ‘mark’, (puts “You are amazing!”) is line 2 in traditional if-then statements. The else is replaced with : in the one liner, and line 4, as you noticed is written (puts “You’re not as amazing as mark.”).

One liner short hand style, as I call these makes a code a ton more dry! Less code to write, more production hopefully! But make sure you understand the concepts of a traditional if-then-else statements before trying out the one liner short hand style, because in the end, the logic behind the code has to make sense!

Like what you read? Give Mark Bui a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.