0
0
Rubyprogramming~5 mins

Range operators (.. and ...) in Ruby

Choose your learning style9 modes available
Introduction

Range operators help you create a list of values between a start and an end point easily.

When you want to count numbers from 1 to 10.
When you need to loop through letters from 'a' to 'z'.
When you want to check if a number falls within a certain range.
When you want to create a sequence of dates between two days.
When you want to slice parts of an array or string using ranges.
Syntax
Ruby
start..end   # Includes end value
start...end  # Excludes end value

The .. operator creates a range including the last value.

The ... operator creates a range excluding the last value.

Examples
Range from 1 to 5 including 5.
Ruby
1..5
# This creates a range including 1, 2, 3, 4, 5
Range from 1 to 5 excluding 5.
Ruby
1...5
# This creates a range including 1, 2, 3, 4 but not 5
Range of letters from 'a' to 'e' including 'e'.
Ruby
'a'..'e'
# This creates a range including 'a', 'b', 'c', 'd', 'e'
Range of letters from 'a' to 'e' excluding 'e'.
Ruby
'a'...'e'
# This creates a range including 'a', 'b', 'c', 'd' but not 'e'
Sample Program

This program shows how the two range operators work by printing numbers from 1 to 5 with and without including 5.

Ruby
puts "Using .. operator:"
(1..5).each { |num| print "#{num} " }

puts "\nUsing ... operator:"
(1...5).each { |num| print "#{num} " }
OutputSuccess
Important Notes

Ranges can be used with numbers, letters, and other objects that can be compared.

Ranges are often used in loops and conditions to simplify code.

Summary

The .. operator creates a range including the end value.

The ... operator creates a range excluding the end value.

Ranges make it easy to work with sequences of values.