uniq_by

Robert Klemme posted this beautiful snippet to ruby-talk yesterday:

module Enumerable
  def uniq_by
    h = {}; inject([]) { |a,x| h[yield(x)] ||= a << x }
  end
end
thus bringing a tear to my eye. The question was: write a uniq_by method that is to uniq by analogy with sort_by to sort, e.g.:

> (1..100).map{ |x| rand 100 }.uniq_by { |x| x % 7 }
=> [70, 4, 22, 16, 24, 33, 55]

Not that I’ve found a use for it, but all the same: beautiful.