[Ruby] I tried to diet the if statement code with the ternary operator


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
Displayed as odd

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.

Prerequisite environment

MacOS Catalina 10.15.7 Ruby 2.6.6

if ~ else statement


n = gets.to_i

if n % 2 == 0
  check_number = "even"
  check_number = "odd"

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

Ternary operator


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! !! !! !! !!

if ~ else statement (no method definition)


n = gets.to_i

if n % 2 == 0
  puts "even"
  puts "odd"

I wrote puts in the if statement without using the method definition. It's a little shorter than the first code.

Ternary operator (no method definition)


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?

Ternary operator (final version)


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!

Recommended Posts

[Ruby] I tried to diet the if statement code with the ternary operator
I tried to solve the problem of "multi-stage selection" with Ruby
Assignment to multiple variables with the ternary operator
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
I tried to get the distance from the address string to the nearest station with ruby
I tried DI with Ruby
[Ruby] problem with if statement
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
I tried to increase the processing speed with spiritual engineering
I tried to summarize the basic grammar of Ruby briefly
I tried to automate LibreOffice Calc with Ruby + PyCall.rb (Ubuntu 18.04)
I tried upgrading from CentOS 6.5 to CentOS 7 with the upgrade tool
I tried to interact with Java
I tried to explain the method
I tried to build the environment of PlantUML Server with Docker
I tried to write code like a type declaration in Ruby
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
I tried to reimplement Ruby Float (arg, exception: true) with builtin
I tried to check the operation of gRPC server with grpcurl
I tried to summarize the methods used
I tried migrating Processing to VS Code
I tried to get started with WebAssembly
I tried to implement the Iterator pattern
I tried to summarize the Stream API
I tried to build Ruby 3.0.0 from source
I tried to implement ModanShogi with Kinx
[Introduction to Java] Conditional branching (if statement, if-else statement, else if statement, ternary operator, switch statement)
I can't build if I set the build destination to a simulator with XCode12!
I tried to make full use of the CPU core in Ruby
I tried to visualize the access of Lambda → Athena with AWS X-Ray
I was addicted to unit testing with the buffer operator in RxJava
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I tried to measure and compare the speed of GraalVM with JMH
I tried to verify AdoptOpenJDK 11 (11.0.2) with Docker image
A memorandum to clean up the code Ruby
Ruby: I tried to find out where Nokogiri goes to see the encoding himself
I tried to manage struts configuration with Coggle
Since the du command used when the capacity is full is difficult to use, I tried wrapping it with ruby
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to manage login information with JMX
I tried to organize the session in Rails
I tried to solve the tribonatch sequence problem in Ruby (time limit 10 minutes)
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
I tried to compare the infrastructure technology of engineers these days with cooking.
I made blackjack with Ruby (I tried using minitest)
The code I used to connect Rails 3 to PostgreSQL 10
[Ruby] Code to display the day of the week
[API] I tried using the zip code search API
[Ruby basics] I tried to learn modules (Chapter 1)
I tried to set tomcat to run the Servlet.
I tried to break a block with java (1)
I checked the number of taxis with Ruby
I want to get the value in Ruby
Sazae-san's rock-paper-scissors I tried to verify the theoretical value and the measured value of the probability of the same hand 5 consecutive times with Ruby
I tried to summarize the points to consider when acquiring location information with the iOS application ③
I tried to check the operation of http request (Put) with Talented API Tester
I tried to summarize the points to consider when acquiring location information with the iOS application ①
I tried to summarize the points to consider when acquiring location information with the iOS application ②
[Swift] I tried to implement Instagram profile-like UI with UICollectionView only with code without storyboard
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver