Enter a number from the terminal and write a program that outputs as follows according to the number.
――If it is 10 or less, it is a number of 10 or less. --If the number is greater than 10, it is "greater than 10" --If it is 10 or less and 0 or less, "It is a number of 0 or less"
ruby.rb
input = gets.to_i
if input <= 0
puts "It is a number less than 0"
elsif <= 10
puts "Is a number less than 10"
else
puts "Is a number greater than 10"
end
I think it was relatively easy to understand how to write numbers from the terminal (to_i) and how to write conditional branches (using elsif and else, using comparison operators). The point of the problem this time is ** which of the three conditions should be described from **.
The if statement is judged from the conditions written earlier. We do not compare all conditional expressions and make a comprehensive judgment. Therefore, if the above conditions are met, the processing of the lower conditions will be skipped even if the lower conditions are met.
In other words, if you write a conditional expression as shown below and the entered number is -3, the first conditional expression will be applied and "10 or less" will be displayed.
ruby.rb
if input <= 10
puts "Is a number less than 10"
elsif input <= 0
puts "It is a number less than 0"
end
When writing conditional expressions, be careful to write the more limited ones first!
Recommended Posts