diff options
| author | Jun Hiroe <[email protected]> | 2014-04-18 21:57:11 +0900 |
|---|---|---|
| committer | Jun Hiroe <[email protected]> | 2014-04-18 23:13:02 +0900 |
| commit | 80646a7890a0e786f7f6f1614a519eccae3b0341 (patch) | |
| tree | 80a6a63b2dee91c9f4767d6c6d7b68ae0bf58f1b /mrbgems/mruby-array-ext/mrblib/array.rb | |
| parent | 4918e5ec65511728594319d389af78a610997eb8 (diff) | |
| download | mruby-80646a7890a0e786f7f6f1614a519eccae3b0341.tar.gz mruby-80646a7890a0e786f7f6f1614a519eccae3b0341.zip | |
Add a block argument with Array#uniq_bang
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 25 |
1 files changed, 20 insertions, 5 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 7f48811f1..0da5d05a8 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -1,7 +1,8 @@ class Array ## # call-seq: - # ary.uniq! -> ary or nil + # ary.uniq! -> ary or nil + # ary.uniq! { |item| ... } -> ary or nil # # Removes duplicate elements from +self+. # Returns <code>nil</code> if no changes are made (that is, no @@ -11,13 +12,27 @@ class Array # a.uniq! #=> ["a", "b", "c"] # b = [ "a", "b", "c" ] # b.uniq! #=> nil + # c = [["student","sam"], ["student","george"], ["teacher","matz"]] + # c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]] # - def uniq! + def uniq!(&block) ary = self.dup result = [] - while ary.size > 0 - result << ary.shift - ary.delete(result.last) + if block + hash = {} + while ary.size > 0 + val = ary.shift + key = block.call(val) + hash[key] = val unless hash.has_key?(key) + end + hash.each_value do |value| + result << value + end + else + while ary.size > 0 + result << ary.shift + ary.delete(result.last) + end end if result.size == self.size nil |
