Ruby can make choose based on data. This is very useful, as programs shouldn’t always do the same. The concept is known as if statements.
This data (variables) are used with a condition: if statements start with a condition. A condition may be (x > 3), (y < 4), (weather = rain).
What do you need these conditions for? Only if a condition is true, code is executed.
If statements are present in your everyday life, some examples:
- if (elevator door is closed), move up or down.
- if (press tv button), next channel
The program below is an example of an if statement.
ruby runs the code block only if the condition (x >2) is true. If you change variable x to any number lower than two, its codeblock is not executed.
Save as example.rb then run with:
You can execute a codeblock if a condition is not true
x = 1
if x > 2
puts "x greater than 2"
puts "executing lines of code (puts)"
puts "other codeblock now"
puts "condition (x > 2) is not true"
Save as example2.rb, run with
Change the variable x and run it several times.
- Make a program that divides x by 2 if it’s greater than 0
- Find out if if-statements can be used inside if-statements.