For Loop with Ranges
Part of the Fundamentals section of Coddy's Ruby journey. Lesson 39 of 88.
Loops let you repeat code multiple times without writing it over and over. In Ruby, the for loop combined with a range is a straightforward way to iterate through a sequence of numbers.
A range in Ruby represents a sequence of values. You create one using two dots between a start and end value. Here's how to loop through numbers 1 to 5:
for i in 1..5
puts i
endThis outputs each number from 1 to 5, each on its own line. The variable i takes on each value in the range, one at a time, and the code inside the loop runs for each value.
Ruby has two types of ranges. The two-dot range 1..5 includes both endpoints (1, 2, 3, 4, 5). The three-dot range 1...5 excludes the last number (1, 2, 3, 4):
for num in 1...4
puts num
end
# Outputs: 1, 2, 3You can use any variable name you like and perform operations inside the loop. For example, printing the square of each number:
for n in 1..3
puts n * n
end
# Outputs: 1, 4, 9Challenge
EasyRead a number n from input. Use a for loop with a range to print all numbers from 1 to n, each on its own line.
The input will be a single integer representing the upper limit of the range.
For example, if the input is 4, the output should be:
1
2
3
4Try it yourself
# Read the number from input
n = gets.to_i
# TODO: Write your code below
# Use a for loop with a range to print all numbers from 1 to nThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or FalsePractice on your own: Online Ruby compiler