One of the operators in programming languages is called the ternary operator (conditional operator). With this, you can write an if statement that spans multiple lines on one line, so you can diet moody code.
This article was written in Ruby code ** "A program that outputs" odd "if the input integer is odd and" even "if it is even" ** You will see how the code written in the if statement is dieted while using the theme.
First, let's create an image of the code we will write!
if numbers are even Display as even else Displayed as odd end
If statement over 5 lines as above
Even numbers?Display as even:Displayed as odd
The feature of the ternary operator is that it can be written in one line.
MacOS Catalina 10.15.7 Ruby 2.6.6
n = gets.to_i if n % 2 == 0 check_number = "even" else check_number = "odd" end puts check_number
When this ruby file is executed in the terminal, it will be as follows. Other than the examples below, odd should be output if it is odd, and even if it is even.
$ ruby if.rb 5 #input odd #output $ ruby if.rb 8 #input even #output
n = gets.to_i check_number = n % 2 == 0 ? "even" : "odd" puts check_number
If you write it with the ternary operator, it will be as above. It's a lot cleaner than using the if ~ else statement! In terms of the number of lines, it is 7 lines → 3 lines, which is less than half.
Just in case, let's run it in the terminal. You can get the same result as the if ~ else statement.
$ ruby ternary.rb 17 #input odd #output $ ruby ternary.rb 24 #input even #output
That's all for learning the ternary operator, but ... Let's continue the diet a little more because it's a big deal! !! !! !! !!
n = gets.to_i if n % 2 == 0 puts "even" else puts "odd" end
puts in the if statement without using the method definition.
It's a little shorter than the first code.
n = gets.to_i puts n % 2 == 0 ? "even" : "odd"
If you write the above notation with the ternary operator, you will get the code like this. There are now two lines! Do you feel greedy when you come to this point and want to write in one line?
puts gets.to_i % 2 == 0 ? "even" : "odd"
I was able to write in one line! !! !! !! !! The code that was originally written in 7 lines is now 1 line. R ○ Z ○ P is also surprised at the 85% OFF diet.
That's it for the code diet using the ternary operator!
2020/01/08 I would like to introduce the suggestions from @scivola (Thank you!)
It will be easier to see if you add parentheses as shown below.
puts (gets.to_i % 2 == 0) ? "even" : "odd"
Since Integer # even? can be used to determine whether an integer is an even number,
puts gets.to_i.even? ? "even" : "odd"
You can also write!
Thank you @scivola!