» Quick Introduction to Ruby » 1. Basics » 1.4 Control Flow

Control Flow

Ruby provides several control structures to manage the flow of your code.

Conditionals

if...elsif..else

x = 10

if x > 5
  puts "x is greater than 5"
elsif x == 5
  puts "x is equal to 5"
else
  puts "x is less than 5"
end

unless

x = 10

unless x > 5
  puts "x is not greater than 5"
else
  puts "x is greater than 5"
end

Case Statements

day = "Wednesday"

case day
when "Monday"
  puts "It's Monday"
when "Wednesday", "Friday"
  puts "It's a midweek day"
else
  puts "It's another day"
end

Loops

while

counter = 0

while counter < 5
  puts counter
  counter += 1
end

until

counter = 0

until counter >= 5
  puts counter
  counter += 1
end

for

for i in 0..4
  puts i
end

each

each is used for iterating over collections.

fruits = ["apple", "banana", "orange"]

fruits.each do |fruit|
  puts fruit
end

Iterators

times

5.times do
  puts "Hello, World!"
end

upto & downto

1.upto(5) do |num|
  puts num
end

5.downto(1) do |num|
  puts num
end

each_with_index

fruits = ["apple", "banana", "orange"]

fruits.each_with_index do |fruit, index|
  puts "#{index + 1}. #{fruit}"
end

Code Challenge

A perfect number is a positive integer that is equal to the sum of its proper divisors, excluding itself. Write a Ruby function to find perfect numbers up to a given limit.

Loading...
> code result goes here
Prev
Next