module RuboCop::Cop::Duplication

Common functionality for dealing with duplication.

Private Instance Methods

consecutive_duplicates(collection) click to toggle source

Returns the consecutive duplicates, leaving out the first instance of the duplicated elements.

@param [Array] collection an array to return consecutive duplicates for @return [Array] the consecutive duplicates

# File lib/rubocop/cop/mixin/duplication.rb, line 31
def consecutive_duplicates(collection)
  grouped_duplicates(collection).flat_map { |items| items[1..-1] }
end
duplicates(collection) click to toggle source

Returns all duplicates, including the first instance of the duplicated elements.

@param [Array] collection an array to return duplicates for @return [Array] all the duplicates

# File lib/rubocop/cop/mixin/duplication.rb, line 22
def duplicates(collection)
  grouped_duplicates(collection).flatten
end
duplicates?(collection) click to toggle source

Whether the `collection` contains any duplicates.

@param [Array] collection an array to check for duplicates @return [Boolean] whether the array contains any duplicates

# File lib/rubocop/cop/mixin/duplication.rb, line 13
def duplicates?(collection)
  collection.size > 1 && collection.size > collection.uniq.size
end
grouped_duplicates(collection) click to toggle source

Returns a hash of grouped duplicates. The key will be the first instance of the element, and the value an `array` of the initial element and all duplicate instances.

@param [Array] collection an array to group duplicates for @return [Array] the grouped duplicates

# File lib/rubocop/cop/mixin/duplication.rb, line 41
def grouped_duplicates(collection)
  collection.group_by { |item| item }.values.reject(&:one?)
end