I learned about unless sentences in a reference book, so I wrote an article.
Please point out if there is a misunderstanding.
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.
age = 16
unless age >= 20
puts "We cannot serve alcohol to minors"
end
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.
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.
・ Ruby on rails 5 that can be used in the field
Recommended Posts