
module Enumerable

  # Like #uniq, but determines uniqueness based on a given block.
  #
  #   (-5..5).to_a.uniq_by {|i| i*i }
  #
  # produces
  #
  #   [-5, -4, -3, -2, -1, 0]
  #
  def uniq_by #:yield:
    h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x}
  end

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_uniq_by
      a = [-5, -4, -3, -2, -1, 0]
      r = (-5..5).to_a.uniq_by{|i| i*i }
      assert_equal( a, r )
    end

  end

=end
