Lesson 2 of 8 · 8 min

Making decisions

temperature = 31

if temperature > 30
  puts "Hot"
elsif temperature > 20
  puts "Warm"
else
  puts "Cool"
end

Note the spelling elsif, and end to close the block. No brackets or colons are needed.

unless and one-line conditions

unless is the opposite of if. Both can also go at the end of a line, which reads naturally for short checks:

puts "Take an umbrella" if raining
puts "All good" unless errors.any?

case

When you compare one value against many options, case is cleaner than a chain of elsif. It works with exact values and with ranges (1..5 means 1 to 5, inclusive):

case mark
when 80..100 then puts "A"
when 60..79  then puts "B"
else              puts "Keep practising"
end

Reading input

gets reads a line of input (from the box above the Run button). It includes the line break, so .chomp removes it; .to_i turns it into a whole number:

name = gets.chomp
items = gets.to_i

Your task

Read a number of items and print the delivery time with a case statement:

Items Print
0 to 2 Ships in 1 day
3 to 9 Ships in 3 days
10 or more Contact us for a quote
main.rb
items = gets.to_i

# print the delivery time

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…