Menu
CoddyTech

Loops and Early Exit

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

C# foreach traverses elements and continue skips the remaining loop body; LINQ can express filtering as a separate pipeline. Ruby each yields to a block, using next to skip an iteration and break to stop. Block return behavior belongs to the called iteration method rather than matching every control-flow rule of a C# loop.

C#: complete program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
int[] values={-2,0,3}; Console.WriteLine(values.Where(x=>x>0).Sum());

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