Land your first dev job — 100% money-back guarantee.
Continue

Range in Ruby

Use Ruby's Range class to represent sequences of values, iterate over them, check membership, and apply ranges in practical use cases like slicing and validation.

Creating Ranges

Ruby has two range operators: `..` (inclusive, includes the end value) and `...` (exclusive, excludes the end value). Ranges work with integers, floats, strings, and any object that implements `<=>` and `succ`.

1. Inclusive Range (..)

`a..b` includes both `a` and `b`.

2. Exclusive Range (...)

`a...b` includes `a` but excludes `b`.

3. String Ranges

Ranges work on strings using alphabetical order.

Iterating Over Ranges

Ranges are Enumerable — you can iterate over them with `each`, step through them with `step`, or use them directly in `for` loops.

1. each

Iterate every value in a range.

2. step

Iterate with a custom step size.

3. map / select on Range

Use Enumerable methods directly on ranges.

Membership & Comparison

Ruby ranges support `include?`, `cover?`, and `===` for membership testing. They are also used in `case` statements for range-based branching.

1. include? vs cover?

`include?` iterates to check membership; `cover?` uses comparison — much faster for large ranges.

2. Ranges in case Statements

Use ranges as conditions in `case/when` for clean branching.

3. clamp

Clamp a value to stay within a range.

Practical Uses

Ranges are used extensively in Ruby for array slicing, pagination, random numbers, and date spans.

1. Array Slicing with Ranges

Use a range as an index to slice arrays.

2. Random Number in Range

Use `rand` with a range to generate bounded random numbers.