Ranges

The range type can be used for representing an interval of values. The intervals could be last item inclusive or last item exclusive:

inclusive = 2..7
exclusive = 2...7

Examples

A range can be many different things, alphabet, time intervals etc. Here's the alphabet example:

a_to_z = 'a'..'z'       # => All letters between A to Z
aa_to_zz = "aa".."zz"   # => All two letter combinations between A to Z

Enumerable and Iterable

The range type implements Enurable and Iterable. These implementations provide useful methods that will let us treat ranges as data collections:

inclusive = 2..7
exclusive = 2...7

# Predicate methods:
p inclusive.includes? 3 # => true
p inclusive.covers? 7   # => true
p 3.in? inclusive       # => true

# Method for summing all the values:
p inclusive.sum # => 27

# A random element within the range:
p inclusive.sample # => 4