Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-range-ext/mrblib/range.rb

raw
1 class Range
2 ##
3 # call-seq:
4 # rng.first -> obj
5 # rng.first(n) -> an_array
6 #
7 # Returns the first object in the range, or an array of the first +n+
8 # elements.
9 #
10 # (10..20).first #=> 10
11 # (10..20).first(3) #=> [10, 11, 12]
12 #
13 def first(*args)
14 raise RangeError, "cannot get the first element of beginless range" if self.begin.nil?
15 return self.begin if args.empty?
16
17 raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 1)" unless args.length == 1
18 nv = args[0]
19 n = nv.__to_int
20 raise ArgumentError, "negative array size (or size too big)" unless 0 <= n
21 ary = []
22 each do |i|
23 break if n <= 0
24 ary.push(i)
25 n -= 1
26 end
27 ary
28 end
29
30 ##
31 # call-seq:
32 # rng.last -> obj
33 # rng.last(n) -> an_array
34 #
35 # Returns the last object in the range,
36 # or an array of the last +n+ elements.
37 #
38 # Note that with no arguments +last+ will return the object that defines
39 # the end of the range even if #exclude_end? is +true+.
40 #
41 # (10..20).last #=> 20
42 # (10...20).last #=> 20
43 # (10..20).last(3) #=> [18, 19, 20]
44 # (10...20).last(3) #=> [17, 18, 19]
45 def last(*args)
46 raise RangeError, "cannot get the last element of endless range" if self.end.nil?
47 return self.end if args.empty?
48
49 raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 1)" unless args.length == 1
50 nv = args[0]
51 n = nv.__to_int
52 raise ArgumentError, "negative array size (or size too big)" unless 0 <= n
53 return self.to_a.last(nv)
54 end
55
56 def max(&block)
57 val = self.begin
58 last = self.end
59 return super(&block) if block
60
61 raise RangeError, "cannot get the maximum of endless range" if last.nil?
62
63 # fast path for numerics
64 if val.kind_of?(Numeric) && last.kind_of?(Numeric)
65 raise TypeError if exclude_end? && !last.kind_of?(Integer)
66 return nil if val > last
67 return nil if val == last && exclude_end?
68
69 max = last
70 max -= 1 if exclude_end?
71 return max
72 end
73
74 # delegate to Enumerable
75 super()
76 end
77
78 def min(&block)
79 val = self.begin
80 last = self.end
81 if block
82 raise RangeError, "cannot get the minimum of endless range with custom comparison method" if last.nil?
83 return super(&block)
84 end
85 return val if last.nil?
86
87 # fast path for numerics
88 if val.kind_of?(Numeric) && last.kind_of?(Numeric)
89 return nil if val > last
90 return nil if val == last && exclude_end?
91
92 min = val
93 return min
94 end
95
96 # delegate to Enumerable
97 super()
98 end
99
100 # Compare two ranges and see if they overlap each other
101 # (1..5).overlap?(4..6) # => true
102 # (1..5).overlap?(7..9) # => false
103 def overlap?(other)
104 raise TypeError, "argument must be a range" unless other.kind_of?(Range)
105 other.begin == self.begin || self.cover?(other.begin) || other.cover?(self.begin)
106 end
107 end