Control Structures


Collapse Content

If Statement

In Ruby, the if statement uses if and end with an optional else or elsif.

energy = 4
if energy > 5
  puts "Great!"
elsif energy == 4
  puts "OK"
else
  puts "Uh Oh!"
end
OK

Since energy is 4, the code prints out "OK".

Ruby Loops

The while loop follows this format:

while condition
   #do stuff here
 end

For example:

counter = 1
while counter <= 5
  puts "iteration #{counter}"
  counter += 1
end

...which prints:

iteration 1
iteration 2
iteration 3
iteration 4
iteration 5

The for loop in Ruby can go through a collection, such as a range, array or hash. It uses the syntax

for item in collection
   #do stuff with item
 end

For example, you can use a for loop and range to print out the same output as before with less code:

for counter in 1..5
  puts "iteration #{counter}"
end
iteration 1
iteration 2
iteration 3
iteration 4
iteration 5

This code printed went through the numbers from 1 to 5 in a range.

Challenge

What will the code print out if energy was 10?

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

You will be given an array of numbers ar. Use print to print each number in the array in the order it appears, unless the number is a multiple of 3. If a number is a multiple of 3, print no3 instead. (You do not need to add spacing when you print.)

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

Contact Us
Sign in or email us at [email protected]