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

Download Free Ruby Ebook

If statements in ruby

Example

The program below is an example of an if statement.

1
2
3
4
5
6
7
#!/usr/bin/ruby

x = 3
if x > 2
puts "x greater than 2"
puts "executing this code block (puts)"
end

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:

1
ruby example.rb

Else

You can execute a codeblock if a condition is not true

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/ruby

x = 1
if x > 2
puts "x greater than 2"
puts "executing lines of code (puts)"
else
puts "other codeblock now"
puts "condition (x > 2) is not true"
end

Save as example2.rb, run with

1
ruby example2.rb

Change the variable x and run it several times.

Exercises

  1. Make a program that divides x by 2 if it’s greater than 0
  2. Find out if if-statements can be used inside if-statements.