Skip to content

Instantly share code, notes, and snippets.

@janxious
Forked from spraints/nmerge.rb
Created February 11, 2012 03:02
Show Gist options
  • Save janxious/1795630 to your computer and use it in GitHub Desktop.
Save janxious/1795630 to your computer and use it in GitHub Desktop.
class Hash
def self.nmerge(*hashes, &block)
keys = hashes.map(&:keys).flatten.uniq
rhashes = hashes.reverse
keys.inject({ }) do |output, key|
if block
output[key] = block.call(key, hashes.map{ |x| x[key]})
else
rhashes.each do |hash|
if hash[key]
output[key] = hash[key]
break
end
end
end
output
end
end
def self.mmerge(*hashes)
hashes.inject { |a,b| a.merge b }
end
def self.lmerge(*hashes)
hashes.inject({}) { |a,b| a.merge! b }
end
def self.tmerge(*hashes)
{}.tap{|blank| hashes.each{|hash| blank.merge!(hash)}}
end
end
require 'benchmark'
one = {:one => 1, :two => 1}
two = {:two => 2, :three => 2}
three = {:three => 3, :four => 3}
puts Hash.nmerge(one, two, three).inspect
puts Hash.mmerge(one, two, three).inspect
puts Hash.lmerge(one, two, three).inspect
puts Hash.tmerge(one, two, three).inspect
Benchmark.bmbm do |x|
x.report('nmerge') { 100000.times { Hash.nmerge one, two, three } }
x.report('mmerge') { 100000.times { Hash.mmerge one, two, three } }
x.report('lmerge') { 100000.times { Hash.lmerge one, two, three } }
x.report('tmerge') { 100000.times { Hash.tmerge one, two, three } }
end
>> ruby nmerge.rb
{:one=>1, :two=>2, :three=>3, :four=>3}
{:one=>1, :two=>2, :three=>3, :four=>3}
{:one=>1, :two=>2, :three=>3, :four=>3}
{:one=>1, :two=>2, :three=>3, :four=>3}
Rehearsal ------------------------------------------
nmerge 1.120000 0.000000 1.120000 ( 1.124069)
mmerge 0.480000 0.010000 0.490000 ( 0.485693)
lmerge 0.320000 0.000000 0.320000 ( 0.379063)
tmerge 0.270000 0.000000 0.270000 ( 0.275908)
--------------------------------- total: 2.200000sec
user system total real
nmerge 1.120000 0.010000 1.130000 ( 1.128885)
mmerge 0.470000 0.000000 0.470000 ( 0.477016)
lmerge 0.280000 0.000000 0.280000 ( 0.287000)
tmerge 0.270000 0.000000 0.270000 ( 0.269606)
>> ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin10.8.0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment