Skip to content

Instantly share code, notes, and snippets.

@danp
Created August 16, 2009 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danp/168544 to your computer and use it in GitHub Desktop.
Save danp/168544 to your computer and use it in GitHub Desktop.
module Enumerable
def uniq_by(&blk)
inject({}) {|h, o| h.update(blk.call(o) => o) }.values
end
end
if $0 == __FILE__
require "rubygems"
require "spec"
class Thing
attr_reader :x
def initialize(x)
@x = x
end
end
describe Enumerable do
describe "uniq_by" do
it "provides an array of unique objects based on the value of a block" do
things = (1..3).map {|n| Thing.new(n) } * 3
things.uniq_by {|t| t.x }.map {|t| t.x }.should == [1, 2, 3]
end
end
end
Spec::Runner::CommandLine.run
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment