Chapter 3.4 Ranges

Range includes the first and most primitive. It holds sequential values, such as numbers between 1 to 9, or letters from A to Z.

Create a range by placing a series of periods between the lower and upper limit of the range.

Example:

developers = 5…90

testers = 20..45

writers = 18..68

When you wish to include the beginning value and the end value in a range of all values, use two periods.

Example: 0..5

The range 0..5 produces this:

0 – 1 – 2 – 3 – 4 – 5

Using three periods in a range excludes the last value in the range.

Example: 0…5

The range 0…5 produces this:

0 – 1 – 2 – 3 – 4

Ranges include a number of ways to test and compare them. The following lists the methods:

  • - Use this operator to compare ranges.
  • eql? - Use this method to compare ranges.

Example:

Test the probability of the range of old and new cars in a showroom:

old_cars = 1...5
new_cars = 1..5
defective_cars = 1...5

puts(old_cars == new_cars)  ---> false

puts(old_cars.eql? (defective_cars)) ---> true

puts(new_cars == defective_cars) ---> false

Ranges are equal if they have the same beginning and end values. Though ranges share the same beginning and end values, values differ with the number of periods in between the range.

You can also test whether a value is included within the range. To test, use the = operator or include? method.

Example:

If you wish to guess a if a number of defective cars is within the range, perform this:

guess_one = 5
guess_two = 8

puts(defective_cars === guess_one)  #true
puts(defective_cars.include?(guess_one)) #true
puts(defective_cars === guess_two) #false
include? method returns any value that is contained with the range of values in the range.
  • Currently 2.96/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
  Flag Inappropriate Content 0 comments