While solving Ruby problems every day, if statements are overwhelmingly used, so I will summarize the idea.
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>
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.
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