class RuboCop::Cop::Lint::DuplicatedKey

This cop checks for duplicated keys in hash literals.

This cop mirrors a warning in Ruby 2.2.

@example

hash = { food: 'apple', food: 'orange' }

Constants

MSG

Public Instance Methods

on_hash(node) click to toggle source
# File lib/rubocop/cop/lint/duplicated_key.rb, line 15
def on_hash(node)
  keys = []

  hash_pairs = *node
  hash_pairs.each do |pair|
    key, _value = *pair
    if keys.include?(key) && key.recursive_basic_literal?
      add_offense(key, :expression)
    end
    keys << key
  end
end