Range Methods
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 7 of 56.
Ranges come with handy methods that save you from writing loops by hand.
include? checks whether a value falls inside the range:
range = 1..10
puts range.include?(5) # true
puts range.include?(11) # falsemin, max, and size work directly on ranges:
puts (1..10).min # 1
puts (1..10).max # 10
puts (1..10).size # 10step iterates over the range jumping by a fixed amount, useful when you don't want every value:
(0..10).step(2) do |n|
puts n
end
# 0, 2, 4, 6, 8, 10And each works just like on arrays:
(1..3).each { |n| puts n * n }
# 1
# 4
# 9Challenge
EasyYou're given an inclusive range and a list of guesses. Score the guesses and summarise the range.
Read two lines:
- Two integers separated by a space:
startandend_value - A comma-separated list of integer guesses
Using the range start..end_value, print:
Hit: <n>, wherenis how many guesses fall inside the range (useinclude?)Span: <n>, wherenis the range'ssizeMultiples of 3 sum: <n>, wherenis the sum of every multiple of 3 in the range (usestepstarting from the first multiple of 3 at or afterstart)
For input 1 10 on the first line and 3,5,11,7,-2 on the second, the output is:
Hit: 3
Span: 10
Multiples of 3 sum: 18(Hits: 3, 5, 7. Multiples of 3 in 1..10: 3+6+9 = 18.)
Cheat sheet
Useful Range methods:
range = 1..10
range.include?(5) # true
range.min # 1
range.max # 10
range.size # 10step iterates jumping by a fixed amount:
(0..10).step(2) { |n| puts n }
# 0, 2, 4, 6, 8, 10each works just like on arrays:
(1..3).each { |n| puts n * n }Try it yourself
start, end_value = gets.chomp.split.map(&:to_i)
guesses = gets.chomp.split(",").map(&:to_i)
# TODO: Hit count via include?, Span via size, sum of multiples of 3 via step
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier