| 1 |
## |
| 2 |
# Range |
| 3 |
# |
| 4 |
# ISO 15.2.14 |
| 5 |
class Range |
| 6 |
## |
| 7 |
# Range is enumerable |
| 8 |
# |
| 9 |
# ISO 15.2.14.3 |
| 10 |
include Enumerable |
| 11 |
|
| 12 |
## |
| 13 |
# Calls the given block for each element of +self+ |
| 14 |
# and pass the respective element. |
| 15 |
# |
| 16 |
# ISO 15.2.14.4.4 |
| 17 |
def each(&block) |
| 18 |
return to_enum :each unless block |
| 19 |
|
| 20 |
val = self.begin |
| 21 |
last = self.end |
| 22 |
|
| 23 |
if val.kind_of?(Integer) && last.nil? |
| 24 |
i = val |
| 25 |
while true |
| 26 |
block.call(i) |
| 27 |
i += 1 |
| 28 |
end |
| 29 |
return self |
| 30 |
end |
| 31 |
|
| 32 |
if val.kind_of?(String) && last.nil? |
| 33 |
if val.respond_to? :__upto_endless |
| 34 |
return val.__upto_endless(&block) |
| 35 |
else |
| 36 |
str_each = true |
| 37 |
end |
| 38 |
end |
| 39 |
|
| 40 |
if val.kind_of?(Integer) && last.kind_of?(Integer) # integers are special |
| 41 |
lim = last |
| 42 |
lim += 1 unless exclude_end? |
| 43 |
i = val |
| 44 |
while i < lim |
| 45 |
block.call(i) |
| 46 |
i += 1 |
| 47 |
end |
| 48 |
return self |
| 49 |
end |
| 50 |
|
| 51 |
if val.kind_of?(String) && last.kind_of?(String) # strings are special |
| 52 |
if val.respond_to? :upto |
| 53 |
return val.upto(last, exclude_end?, &block) |
| 54 |
else |
| 55 |
str_each = true |
| 56 |
end |
| 57 |
end |
| 58 |
|
| 59 |
raise TypeError, "can't iterate" unless val.respond_to? :succ |
| 60 |
|
| 61 |
return self if (val <=> last) > 0 |
| 62 |
|
| 63 |
while (val <=> last) < 0 |
| 64 |
block.call(val) |
| 65 |
val = val.succ |
| 66 |
if str_each |
| 67 |
break if val.size > last.size |
| 68 |
end |
| 69 |
end |
| 70 |
|
| 71 |
block.call(val) if !exclude_end? && (val <=> last) == 0 |
| 72 |
self |
| 73 |
end |
| 74 |
|
| 75 |
# redefine #hash 15.3.1.3.15 |
| 76 |
def hash |
| 77 |
h = first.hash ^ last.hash |
| 78 |
h += 1 if self.exclude_end? |
| 79 |
h |
| 80 |
end |
| 81 |
|
| 82 |
## |
| 83 |
# call-seq: |
| 84 |
# rng.to_a -> array |
| 85 |
# rng.entries -> array |
| 86 |
# |
| 87 |
# Returns an array containing the items in the range. |
| 88 |
# |
| 89 |
# (1..7).to_a #=> [1, 2, 3, 4, 5, 6, 7] |
| 90 |
# (1..).to_a #=> RangeError: cannot convert endless range to an array |
| 91 |
def to_a |
| 92 |
a = __num_to_a |
| 93 |
return a if a |
| 94 |
super |
| 95 |
end |
| 96 |
alias entries to_a |
| 97 |
end |