Logics

Let’s dive into Ruby's control structures, iterators, and exceptions.

Method calls are statements. Ruby also provides a number of ways to make decisions that affect the repetition and order in which methods are invoked.

Control structures

Ruby has all the usual control structures, such as if statements and while loops. Java, C, and Perl programmers may get caught by the lack of braces around the bodies of these statements though, since Ruby uses the end keyword to signify the end of a body:

Press + to interact
count = 9 # You can play around with this
tries = 3 # You can play around with this
if count > 10
puts "Try again"
elsif tries == 3
puts "You lose"
else
puts "Enter a number"
end

Similarly, while statements are terminated with end:

Press + to interact
weight = 2 # You can play around with these values
num_pallets = 10 # You can play around with these values
while weight < 100 and num_pallets <= 30
weight += 1
num_pallets += 1
end
puts num_pallets

Ruby also contains variants of these statements. The unless statement is like if except that it checks for the condition to not be true. Similarly, until ...