Ranges

A Range object represents the values between a start value and an end value. Range literals are written by placing two or three dots between the start and end value. If two dots are used, then the range is inclusive and the end value is part of the range. If three dots are used, then the range is exclusive and the end value is not part of the range:

1..10      # The integers 1 through 10, including 10
1.0...10.0 # The numbers between 1.0 and 10.0, excluding 10.0 itself

Test whether a value is included in a range with the include? method (but see below for a discussion of alternatives):

cold_war = 1945..1989
cold_war.include? birthdate.year

Implicit in the definition of a range is the notion of ordering. If a range is the values between two endpoints, there obviously must be some way to compare values to those endpoints. In Ruby, this is done with the comparison operator <=>, which compares its two operands and evaluates to –1, 0, or 1, depending on their relative order (or equality). Classes such as numbers and strings that have an ordering define the <=> operator. A value can only be used as a range endpoint if it responds to this operator. The endpoints of a range and the values “in” the range are typically all of the same class. Technically, however, any value that is compatible with the <=> operators of the range endpoints can be considered a member of the range.

The primary purpose for ranges is comparison: to be able to determine whether a value is in or out of the range. An ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.