Menu
CoddyTech

Loops and Early Exit

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

R next skips one loop iteration and break stops the loop; Ruby uses the same names within common iteration contexts. Ruby each is a method yielding to a block rather than an R for statement. R vectors support vectorized selection as another option, but that is not the same control-flow contract as early stopping. Preserve sentinel behavior separately from filtering.

R: complete program

values <- c(-2,0,3); cat(sum(values[values>0]),"\n",sep="")

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

Practice on your own: Online Ruby compiler