Menu
CoddyTech

Case and Ranges

Lesson 10 of 48 in Coddy's Ruby for Python Developers course.

Ruby case compares each pattern using its case-equality operation. A range in a when branch checks membership; this is different from Python structural pattern matching syntax. Two dots form an inclusive range, while three dots exclude the endpoint. Ranges can also drive iteration. Cases are considered in order, so overlapping branches select the first match. This example classifies a character and separately enumerates an exclusive integer range.

Python: complete program

letter = "e"
print("vowel" if letter in "aeiou" else "other")
print(" ".join(str(n) for n in range(2, 5)))

Ruby: complete program

letter = "e"
puts(case letter
when "a", "e", "i", "o", "u" then "vowel"
else "other"
end)
puts (2...5).to_a.join(" ")
challenge icon

Challenge

Easy

Read an integer score 0..100. Return low for 0..39, middle for 40..79, high for 80..100.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
def check(value)
  raise 'Public API check failed' unless value
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for Python Developers

Practice on your own: Online Ruby compiler