Skip to content

Instantly share code, notes, and snippets.

@bakineggs
Created August 1, 2009 20:31
Embed
What would you like to do?
a patch is available at http://bakineggs.com/0001-Array-uniq-can-take-a-block.patch
dan@dan:~$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'active_support'
=> true
irb(main):003:0> class Array
irb(main):004:1> def uniq_with_block
irb(main):005:2> return uniq_without_block unless block_given?
irb(main):006:2> aggregator = {}
irb(main):007:2> each do |element|
irb(main):008:3* aggregator[yield(element)] ||= element
irb(main):009:3> end
irb(main):010:2> aggregator.values
irb(main):011:2> end
irb(main):012:1> alias_method_chain :uniq, :block
irb(main):013:1> def uniq_by
irb(main):014:2> select{ |item| select{|i| yield(i) == yield(item)}.index(item) == 0 }
irb(main):015:2> end
irb(main):016:1> end
irb(main):017:0> start = Time.now; (1..1000).to_a.uniq {|x| x % 1000}; Time.now - start
=> 0.001999
irb(main):018:0> start = Time.now; (1..10000).to_a.uniq {|x| x % 1000}; Time.now - start
=> 0.014277
irb(main):019:0> start = Time.now; (1..100000).to_a.uniq {|x| x % 1000}; Time.now - start
=> 0.135073
irb(main):020:0> start = Time.now; (1..1000000).to_a.uniq {|x| x % 1000}; Time.now - start
=> 1.386128
irb(main):021:0> start = Time.now; (1..10000000).to_a.uniq {|x| x % 1000}; Time.now - start
=> 35.404049
irb(main):022:0> start = Time.now; (1..1000).to_a.uniq_by {|x| x % 1000}; Time.now - start
=> 1.251658
irb(main):023:0> start = Time.now; (1..10000).to_a.uniq_by {|x| x % 1000}; Time.now - start
=> 124.187849
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment