Loops and Early Exit
Lesson 11 of 48 in Coddy's Ruby for Java Developers course.
Java enhanced for traverses arrays or Iterable objects; Ruby each yields elements to a block. Java continue corresponds to Ruby next in this setting, and break exits the loop. Ruby iteration methods are calls with blocks, so their return and closure behavior should not be assumed to match every Java loop statement.
Java: complete program
import java.util.*;
public class Main {
public static void main(String[] args) {
for (String word : List.of("red", "skip", "blue")) {
if (word.equals("skip")) continue;
System.out.println(word);
}
}
}Ruby: complete program
["red", "skip", "blue"].each do |word|
next if word == "skip"
puts word
endChallenge
EasyInput 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Ruby for Java Developers
1Start with Ruby
Run Ruby FilesOutput and CommentsNames and ObjectsInteger ArithmeticTruth and Boolean LogicString OperationsSymbols and KeysRecap: Packing Slip2Flow and Methods
Conditional ValuesCase and RangesLoops and Early ExitMethods and ReturnsDefaults and KeywordsRecap: Sensor Run5Objects and State
Modules as NamespacesClasses and InstancesReaders and WritersValidated ConstructionRecap: Wallet8Lending Desk Project
Lending Desk: CatalogLending Desk: BorrowPractice on your own: Online Ruby compiler