Menu
CoddyTech

Loops and Early Exit

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

C for traverses arrays using an index and length, and continue skips the remaining loop body. Ruby each yields elements to a block, where next advances to the next iteration and break stops traversal. Iteration methods are calls with blocks, so their return and closure behavior differs from C loop statements.

C: complete program

#include <stdio.h>

int main(void)
{
    const int values[] = {-2, 0, 3};
    int total = 0;
    size_t count = sizeof values / sizeof values[0];
    for (size_t i = 0; i < count; ++i) {
        if (values[i] <= 0) {
            continue;
        }
        total += values[i];
    }
    printf("%d\n", total);
    return 0;
}

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

Practice on your own: Online Ruby compiler