Ranges in Ruby Language
Ranges in Ruby are a versatile and powerful feature that allow you to express a range of values between a start
and end point. They are commonly used for tasks such as iterating over a sequence of numbers, selecting a portion of an array, and checking if a value falls within a certain range. In this post, we’ll explore the basics of ranges in Ruby, their syntax, and various use cases.Creating Ranges
In Ruby, you can create a range using two dots ..
or three dots ...
. The two-dot range includes both the start and end values, while the three-dot range includes the start value but excludes the end value.
Inclusive Range (..)
inclusive_range = 1..5
# This range includes 1, 2, 3, 4, and 5
Exclusive Range (…)
exclusive_range = 1...5
# This range includes 1, 2, 3, and 4 (excludes 5)
Range as a Sequence
Ranges are often used to create sequences of numbers. You can iterate over these sequences, making your code more concise and readable.
(1..5).each do |num|
puts num
end
# Output:
# 1
# 2
# 3
# 4
# 5
Range as a Condition
Ranges are also useful for checking if a value falls within a specific range.
temperature = 25
if (0..32).include?(temperature)
puts "It's freezing!"
elsif (33..70).include?(temperature)
puts "It's comfortable."
else
puts "It's hot outside!"
end
Range with Arrays
You can use ranges to select a portion of an array, which is a common operation in Ruby.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
selected_numbers = numbers[2..5]
# selected_numbers will contain [3, 4, 5, 6]
Custom Objects
Ranges are not limited to integers; you can use custom objects as well, as long as they define the <=>
(spaceship) operator to compare values.
date_range = Date.new(2023, 1, 1)..Date.new(2023, 12, 31)
Infinite Ranges
Ruby allows you to create infinite ranges, which can be useful for lazy enumeration.
infinite_range = 1..Float::INFINITY
infinite_range.each do |number|
break if number > 10
puts number
end
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.