Ruby/Range/Range Creation

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Reference to_a from a letter-based range

range = "a".."e"         #creates "a", "b", "c", "d", "e"
puts range.to_a



Reference to_a from a range

range = 1..5             #creates 1, 2, 3, 4, 5
puts range.to_a



Reference to_a from a range in an excluded range

range = 1...5            #excludes the 5
puts range.to_a



To create a range, use the .. operator. For example, here"s how you might create the range 1 to 4:

my_range = 1..4
puts my_range



use the ... operator, which is the same thing except that the final item in the range is omitted

my_new_range = 1...4
puts my_new_range



Variable based range

x = 2
puts x+1..x*x



what are Ranges

Ruby has ranges, with range operators and a Range class. 
Ranges are intervals with a start value and an end value, separated by a range operator. 
There are two range operators, .. (two dots) and ... (three dots). 
The range operator .. means an inclusive range of numbers. 
1..10 means a range of numbers from 1 to 10, including 10 (1, 2, 3, 4, 5, 6, 7, 9, 10). 
The range operator ... means an exclusive range of numbers that exclude the last in the series; 
in other words, 1...10 means a range of numbers from 1 to 9, as the 10 at the end of the range is excluded (1, 2, 3, 4, 5, 6, 7, 9).
The === method determines if a value is a member of, or included in, a range
(1..25) === 14 # => true, in range
(1..25) === 26 # => false, out of range
(1...25) === 25 # => false, out of range if ... used



With the Range class, you can also create a range

digits = Range.new(1, 9)
digits.to_a # => [1, 2, 3, 4, 5, 6, 7, 8, 9]



You have to create ranges in ascending sequence

(1..10).to_a
this will give you an empty array:
(10..1).to_a