Things to keep in mind when using if statements

Introduction

While solving Ruby problems every day, if statements are overwhelmingly used, so I will summarize the idea.

Things to think about when using an if statement

  1. Whether the return value is a boolean value
  2. Order of conditional statements
  3. Whether to add else

1. Whether the return value is a boolean value

The conditional statement must contain a boolean value. For example

str = "abc"
if str.include?("a")
  puts "OK"
end

if str
  puts "NG"
end

The include? Method returns false if it has an argument, otherwise it does not have true. Therefore, since there is a in the first if statement, true is returned and the process is executed. However, the second if statement does not work because the conditional statement is just a variable.

Consider whether the conditional statement is a method that determines whether it is true or false </ font>

2. Order of conditional statements

if conditional statement 1
  #Processing when conditional statement 1 is true
elsif conditional statement 2
  #Processing when conditional statement 2 is true
else
  #Processing when neither conditional statement 1 nor conditional statement 2 applies
end

The order in which the conditional statements are written is very important! </ font> Since the code is read in order from the top, conditional statement 2 is not read when conditional statement 1 is true.

3. Whether to add else

If you want to process when none of the conditions are met, add it. If there is only one conditional statement and you only need to process it, you do not need to add else. </ font>

Recommended Posts