[RAILS] [Ruby] Conditional bifurcation unless statement

I learned about unless sentences in a reference book, so I wrote an article.

Please point out if there is a misunderstanding.

What is an unless statement?

The if statement executes processing when the result of the condition is true, but on the contrary, there is a processing syntax called unless statement which executes processing when the result of the condition is false.

You can find if about here. https://qiita.com/muffin-men/items/fd8637bb1b98cb369c5b

This time I would like to compare the unless statement / if statement. Let's use the code below.

unless statement

age = 16
unless age >= 20
  puts "We cannot serve alcohol to minors"
end

if statement

age = 16
if age < 20
  puts "We cannot serve alcohol to minors"
end

The unless statement is used by reversing the if condition, and what can be expressed by the unless statement can also be expressed by the if statement. If you can write the same thing, you will be wondering which one to use.

In the above code, when it is unless, you are conscious of whether you are over 20 years old (if it is different), while when it is if, you are conscious of whether you are under 20 years old. If you make heavy use of the condition that you are over 20 years old, it is easy to understand the unless sentence that you can write it as it is.

Summary

Basically, it is easy to use the if statement, but select unless to use the one that is easy to understand intuitively as the content of the condition.

Reference book

・ Ruby on rails 5 that can be used in the field

Recommended Posts

[Ruby] Conditional bifurcation unless statement
[Ruby] conditional branch if statement
[Ruby] if statement concept of conditional expression
Ruby conditional branch. if, conditional operator (ternary operator), unless, case
Ruby conditional branch processing
About Ruby if statement
Ruby Learning # 16 Return Statement
Ruby study memo (conditional branching)
Swift conditional branch statement summary
[Ruby] Conditional branching Conditional expression order
[Ruby] Introduction to Ruby Error statement
[Ruby] problem with if statement
Creating a mixed conditional expression of Rails if statement and unless
Memorandum (other conditional bifurcation, iterative processing)
Java study # 4 (conditional branching / if statement)