Menu
CoddyTech

Loops and Early Exit

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

Lua has no continue statement in the Lua 5.1-compatible subset used here, so a conditional can skip work inside the loop. Ruby next skips the remaining block iteration. Lua ipairs traverses the sequence until an absent entry, unlike pairs traversal of general table keys. These examples use a dense sequence with no holes.

Lua: complete program

for _, word in ipairs({"red", "skip", "blue"}) do
  if word ~= "skip" then print(word) end
end

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

Practice on your own: Online Ruby compiler