Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/activefacts/support.rb

Overview

Return all duplicate objects in the array (using hash-equality)

Instance Method Summary collapse

Instance Method Details

#__orig_indexObject

Fake up Ruby 1.9’s Array#index method, mostly



121
# File 'lib/activefacts/support.rb', line 121

alias_method :__orig_index, :index

#duplicates(&b) ⇒ Object



109
110
111
112
113
114
115
116
117
# File 'lib/activefacts/support.rb', line 109

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.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/activefacts/support.rb', line 135

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



122
123
124
125
126
127
128
129
# File 'lib/activefacts/support.rb', line 122

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