Loops and Early Exit
Lesson 11 of 48 in Coddy's Ruby for GDScript Developers course.
GDScript for and while use continue to skip one iteration and break to stop. Ruby each yields to a block, where next skips and break stops traversal. The iteration method owns the block call and can have different return behavior from a source loop statement. Keep sentinel stopping separate from filtering invalid items so later data is visited only when intended.
GDScript: complete program
extends SceneTree
func _init():
var total = 0
for line in ["4", "-2", "7", "STOP", "9"]:
if line == "STOP":
break
var value = int(line)
if value <= 0:
continue
total += value
print(total)
quit()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 GDScript 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