diff options
| author | Kouki Ooyatsu <[email protected]> | 2013-03-22 16:39:48 +0900 |
|---|---|---|
| committer | Kouki Ooyatsu <[email protected]> | 2013-03-22 16:45:12 +0900 |
| commit | 0f61d1d6b7a580262ab2f7ce7284e387079a0c00 (patch) | |
| tree | 35ca0e7d023fafeb3d3e771194c4e4624e9eaf11 /mrbgems/mruby-array-ext/mrblib/array.rb | |
| parent | b547a7ed2cc781500a572b3a24fdfba7aed85e40 (diff) | |
| download | mruby-0f61d1d6b7a580262ab2f7ce7284e387079a0c00.tar.gz mruby-0f61d1d6b7a580262ab2f7ce7284e387079a0c00.zip | |
add method(uniq, -, |, &, flatten, compact) and test of Array to mruby-array-ext
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb new file mode 100644 index 000000000..83eaaa35e --- /dev/null +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -0,0 +1,73 @@ +class Array + def uniq! + ary = self.dup + result = [] + while ary.size > 0 + result << ary.shift + ary.delete(result.last) + end + self.replace(result) + end + + def uniq + self.dup.uniq! + end + + def -(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + hash = {} + array = [] + elem.each { |x| hash[x] = true } + self.each { |x| array << x unless hash[x] } + array + end + + def |(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + (self + elem).uniq! + end + + def &(elem) + raise TypeError, "can't convert to Array" unless elem.class == Array + + hash = {} + array = [] + elem.each{|v| hash[v] = true } + self.each do |v| + if hash[v] + array << v + hash.delete v + end + end + array + end + + def flatten(depth=nil) + ar = [] + self.each do |e| + if e.is_a?(Array) && (depth.nil? || depth > 0) + ar += e.flatten(depth.nil? ? nil : depth - 1) + else + ar << e + end + end + ar + end + + def flatten! + self.replace(self.flatten) + end + + def compact + result = self.dup + result.compact! + result + end + + def compact! + result = self.select { |e| e != nil } + self.replace(result) + end +end |
