Things to note in conditional expressions

【Overview】

1. Conclusion </ b>

2. Specific example </ b>

  1. Conclusion

It will be read from the top, so be careful of the order of writing ! </ b>

  1. Specific example

For example, let's look at the case of writing a program that outputs based on the following three conditions.

❶ If it is 20 or less, output "a number of 20 or less" ❷ If the number is greater than 20, output "number greater than 20" ❸ If it is 20 or less and 0 or less, output as "0 or less number"

In this case, the following description is given.

int = gets.to_i

if int <= 20
  puts "Numbers less than 20" #❶
elsif int <= 0
  puts "Numbers less than or equal to 0" #❷
else
  puts "Numbers greater than 20" #❸
end

In this case, if you write "-1" in int, ❶

if int <= 20
  puts "Numbers less than 20"

Reacts, and the output of ❷ that I originally wanted to output is not output. This is because the program is loaded from top to bottom. (There are exceptions such as def being read later and javascript function declarations being read first.)

So change the order of ❶ and ❷

int = gets.to_i

if int <= 0
  puts "Numbers less than or equal to 0" #❶
elsif int <= 20
  puts "Numbers less than 20"  #❷
else
  puts "Numbers greater than 20" #❸
end

Then, it will be a program that captures the original intention.

Recommended Posts