according to JIS/ISO, Array is not Comparable
[mruby.git] / mrblib / array.rb
bloba7f172879c7f887dfe59ddbd2c8dd220aadb04fd
1 ##
2 # Array
4 # ISO 15.2.12
5 class Array
7   ##
8   # Calls the given block for each element of +self+
9   # and pass the respective element.
10   #
11   # ISO 15.2.12.5.10
12   def each(&block)
13     return to_enum :each unless block_given?
15     idx, length = -1, self.length-1
16     while idx < length and length <= self.length and length = self.length-1
17       elm = self[idx += 1]
18       unless elm
19         if elm == nil and length >= self.length
20           break
21         end
22       end
23       block.call(elm)
24     end
25     self
26   end
28   ##
29   # Calls the given block for each element of +self+
30   # and pass the index of the respective element.
31   #
32   # ISO 15.2.12.5.11
33   def each_index(&block)
34     return to_enum :each_index unless block_given?
36     idx = 0
37     while(idx < length)
38       block.call(idx)
39       idx += 1
40     end
41     self
42   end
44   ##
45   # Calls the given block for each element of +self+
46   # and pass the respective element. Each element will
47   # be replaced by the resulting values.
48   #
49   # ISO 15.2.12.5.7
50   def collect!(&block)
51     return to_enum :collect! unless block_given?
53     self.each_index{|idx|
54       self[idx] = block.call(self[idx])
55     }
56     self
57   end
59   ##
60   # Alias for collect!
61   #
62   # ISO 15.2.12.5.20
63   alias map! collect!
65   ##
66   # Private method for Array creation.
67   #
68   # ISO 15.2.12.5.15
69   def initialize(size=0, obj=nil, &block)
70     raise TypeError, "expected Integer for 1st argument" unless size.kind_of? Integer
71     raise ArgumentError, "negative array size" if size < 0
73     self.clear
74     if size > 0
75       self[size - 1] = nil  # allocate
77       idx = 0
78       while(idx < size)
79         self[idx] = (block)? block.call(idx): obj
80         idx += 1
81       end
82     end
84     self
85   end
87   ##
88   # Delete element with index +key+
89   def delete(key, &block)
90     while i = self.index(key)
91       self.delete_at(i)
92       ret = key
93     end
94     if ret == nil && block
95       block.call
96     else
97       ret
98     end
99   end
101   # internal method to convert multi-value to single value
102   def __svalue
103     case self.size
104     when 0
105       return nil
106     when 1
107       self[0]
108     else
109       self
110     end
111   end
115 # Array is enumerable
116 class Array
117   # ISO 15.2.12.3
118   include Enumerable
120   ##
121   # Sort all elements and replace +self+ with these
122   # elements.
123   def sort!(&block)
124     self.replace(self.sort(&block))
125   end