Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/activefacts/support.rb
Overview
Return all duplicate objects in the array (using hash-equality)
Instance Method Summary collapse
-
#__orig_index ⇒ Object
Fake up Ruby 1.9’s Array#index method, mostly.
- #duplicates(&b) ⇒ Object
-
#elide_repeated_subsequences(&compare_block) ⇒ Object
If any element, or sequence of elements, repeats immediately, delete the repetition.
- #index(*a, &b) ⇒ Object
Instance Method Details
#__orig_index ⇒ Object
Fake up Ruby 1.9’s Array#index method, mostly
21 |
# File 'lib/activefacts/support.rb', line 21 alias_method :__orig_index, :index |
#duplicates(&b) ⇒ Object
9 10 11 12 13 14 15 16 17 |
# File 'lib/activefacts/support.rb', line 9 def duplicates(&b) inject({}) do |h,e| h[e] ||= 0 h[e] += 1 h end.reject do |k,v| v == 1 end.keys end |
#elide_repeated_subsequences(&compare_block) ⇒ Object
If any element, or sequence of elements, repeats immediately, delete the repetition. Note that this doesn’t remove all re-occurrences of a subsequence, only consecutive ones. The compare_block allows a custom equality comparison.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/activefacts/support.rb', line 35 def elide_repeated_subsequences &compare_block compare_block ||= lambda{|a,b| a == b} i = 0 while i < size # Need to re-evaluate size on each loop - the array shrinks. j = i #puts "Looking for repetitions of #{self[i]}@[#{i}]" while tail = self[j+1..-1] and k = tail.index {|e| compare_block.call(e, self[i]) } length = j+1+k-i #puts "Found at #{j+1+k} (subsequence of length #{j+1+k-i}), will need to repeat to #{j+k+length}" if j+k+1+length <= size && compare_block[self[i, length], self[j+k+1, length]] #puts "Subsequence from #{i}..#{j+k} repeats immediately at #{j+k+1}..#{j+k+length}" slice!(j+k+1, length) j = i else j += k+1 end end i += 1 end self end |
#index(*a, &b) ⇒ Object
22 23 24 25 26 27 28 29 |
# File 'lib/activefacts/support.rb', line 22 def index *a, &b if a.size == 0 raise "Not faking Enumerator for #{RUBY_VERSION}" if !b (0...size).detect{|i| return i if b.call(self[i]) } else __orig_index(*a, &b) end end |