Menu
CoddyTech

Loops and Early Exit

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

Ruby offers while, until and block-based iteration such as each and times. Python continue corresponds to Ruby next, and both languages use break to leave a loop. Prefer iteration over a collection when a separate index would serve no purpose. A next skips the rest of the current iteration; it does not terminate the whole traversal. The example skips one symbol without accumulating or transforming any numeric state.

Python: complete program

for word in ["red", "skip", "blue"]:
    if word == "skip":
        continue
    print(word)

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

Practice on your own: Online Ruby compiler