Merge pull request #1046 from monaka/pr-add-configuration-macro-MRB_PARSER_BUF_SIZE
[mruby.git] / mrbgems / mruby-array-ext / mrblib / array.rb
blobb3ff9bfca88f485719033fefe5b6f60da03577d4
1 class Array
2   def uniq!
3     ary = self.dup
4     result = []
5     while ary.size > 0
6       result << ary.shift
7       ary.delete(result.last)
8     end
9     if result.size == self.size
10       nil
11     else
12       self.replace(result)
13     end
14   end
16   def uniq
17     ary = self.dup
18     ary.uniq!
19     ary
20   end
22   def -(elem)
23     raise TypeError, "can't convert to Array" unless elem.class == Array
25     hash = {}
26     array = []
27     elem.each { |x| hash[x] = true }
28     self.each { |x| array << x unless hash[x] }
29     array
30   end
32   def |(elem)
33     raise TypeError, "can't convert to Array" unless elem.class == Array
35     ary = self + elem
36     ary.uniq! or ary
37   end
39   def &(elem)
40     raise TypeError, "can't convert to Array" unless elem.class == Array
42     hash = {}
43     array = []
44     elem.each{|v| hash[v] = true }
45     self.each do |v|
46       if hash[v]
47         array << v
48         hash.delete v
49       end
50     end
51     array
52   end
54   def flatten(depth=nil)
55     ar = []
56     self.each do |e|
57       if e.is_a?(Array) && (depth.nil? || depth > 0)
58         ar += e.flatten(depth.nil? ? nil : depth - 1)
59       else
60         ar << e
61       end