[Ruby] Conditional branching Conditional expression order

problem

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"

answer

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

point

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

[Ruby] Conditional branching Conditional expression order
Ruby study memo (conditional branching)
[Ruby] if statement concept of conditional expression
Ruby regular expression
[Ruby] Behavior of evaluation of conditional expression in while
Ruby conditional branch processing
java learning (conditional expression)
Program using conditional branching
Conditional branching of numbers
Also complicated conditional branching
[Ruby] How to use standard output in conditional branching
[Ruby] Conditional bifurcation unless statement
A little complicated conditional branching
java (conditional branching and repetition)
[Ruby] conditional branch if statement
Basics of conditional branching and return
Conditional branching with a flowing interface
Java study # 4 (conditional branching / if statement)