Menu
CoddyTech

Loops and Early Exit

Lesson 11 of 48 in Coddy's Ruby for Luau Developers course.

Luau supports continue to skip an iteration and break to stop, including in numeric and generic loops. Ruby each yields elements to a block, where next skips and break stops. A block belongs to a method call and has distinct return rules from a loop statement. Keep early stopping separate from ordinary filtering.

Luau: complete program

local total=0;for n=1,4 do if n==2 then continue end;total+=n end;print(total)

Ruby: complete program

["red", "skip", "blue"].each do |word|
  next if word == "skip"
  puts word
end
challenge icon

Challenge

Easy

Input is a whitespace sequence of integers. Add values until the first negative value; exclude that value and everything after it. Empty input returns zero.

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 Luau Developers

Practice on your own: Online Ruby compiler