Menu
CoddyTech

Loops and Early Exit

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

Dart for-in loops use continue to skip and break to stop; Iterable.where can express filtering separately. Ruby each yields to a block, using next to skip and break to exit. Iteration methods are calls with block-specific return behavior. Translate the actual control flow rather than assuming every loop keyword has identical surrounding semantics.

Dart: complete program


void main() {
final values=[-2,0,3]; print(values.where((x)=>x>0).fold<int>(0,(int a,int b)=>a+b));
}

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

Practice on your own: Online Ruby compiler