Case and Ranges
Lesson 10 of 48 in Coddy's Ruby for Lua Developers course.
Lua normally uses if chains or dispatch tables rather than a switch statement. Ruby case supports several pattern forms, including ranges, and selects the first matching when branch without fall-through. Lua numeric for includes its upper limit; Ruby three-dot ranges exclude theirs. The loops below deliberately choose equivalent values using different endpoints.
Lua: complete program
local letter = "e"
print(string.find("aeiou", letter, 1, true) and "vowel" or "other")
local values = {}
for n = 2, 4 do values[#values + 1] = n end
print(table.concat(values, " "))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
EasyRead 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Lua Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler