Created
August 16, 2009 03:39
-
-
Save danp/168544 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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