Ruby Range

Range is everywhere: a to z, 0 to 9, and so on. Ruby supports scope and allows us to use scope in different ways:

  • As a range of sequences
  • Scope as a condition
  • As a range of intervals

as a range of sequences

The first and most common use of the

range is to express sequences. A sequence has a starting point, an ending point, and a way to produce a continuous value in the sequence.

Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-point form creates a range containing the specified highest value, and the three-point form creates a range that does not contain the specified highest value.

(1..5) #==> 1, 2, 3, 4, 5 (1.. .5) #==> 1, 2, 3, 4 ('a'..'d') #==> 'a', 'b', 'c', 'd'

Sequence 1..100 is an Range object that contains references to two Fixnum objects. If you want, you can use the to_a method to convert the range to a list. Try the following example:


#!/usr/bin/ruby $,=" , " # Array Value Separator range1 = (1..10).to_a range2 = ('bar'..'bat ').to_a puts "#{range1}" puts "#{range2}"

The above example runs the output as:

[1, 2, 3, 4, 5,  6, 7,  8, 9, 10]
["bar", "bas", "bat"]

scope implements methods that let you traverse them, and you can check their contents in several ways:


#!/usr/bin/ruby # -*- coding: UTF-8 -*- # Specified digits = 0. .9 puts digits.include?(5) ret= digits.min puts "Minimum is #{ret}" ret= digits.max puts "Maximum value is #{ret}" ret= digits.reject {|i| i < 5 } puts "#{ret}" digits.each do |digit| puts "In the loop #{digit}" end

The above example runs the output as:

Minimum is 0
Maximum 9
Unqualified [5, 6, 7, 8, 9]
in the loop 0
in the loop 1
In the loop 2
in the loop 3
in the loop 4
in the loop 5
in the loop 6
in the loop 7
in the loop 8
in the loop 9

Scope as a condition


range can also be used as a conditional expression. For example, the following code snippet prints lines from standard input, where the first line of each collection contains the word start and the last line contains the word end.:


while gets print if /start/../end/ end

scope can be used in a case statement:


#!/usr/bin/ruby # -*- coding: UTF-8 -*- score= 70 result = case score when 0..40 "bad score" when 41..60 "Currently Pass" when 61..70 "pass score" when 71..100 "Good Score" else "wrong score" end puts result

The above example runs the output as:

pass score

as the range of intervals

The last use of the range is interval detection: check if the specified value is within the specified range. You need to use the === equality operator to complete the calculation.


#!/usr/bin/ruby # -*- coding: UTF-8 -*- if ((1..10) === 5) puts "5 in (1..10)" end if (('a'..'j') === 'c') puts "c in ('a'..'j')" end if (('a'..'j') === 'z') puts "z in ('a'..'j')" end

The above example runs the output as:

5 on (1..10)
c on ('a'..'j') 

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.