From: Eric Hodel Date: 2007-01-25T19:27:51+09:00 Subject: Re: can it be shorter? --Apple-Mail-2-287622042 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; format=flowed On Jan 24, 2007, at 15:20, Vincent Fourmond wrote: > Vincent Fourmond wrote: >> h = {} >> for k,v in hash >> [k].flatten.each {|l| h[l] = v} >> end >> hash = h > > Actually, I've got shorter ;-): > > h = {} > for k,v in hash > [*k].each {|l| h[l] = v} > end > hash = h but fastest (I assume all entries worked correctly): $ ruby bm.rb Rehearsal -------------------------------------------------------- original 10.440000 0.010000 10.450000 ( 10.492738) original clean 11.480000 0.040000 11.520000 ( 11.632237) vince 5.210000 0.010000 5.220000 ( 5.264394) william 12.760000 0.020000 12.780000 ( 12.814230) daniel 6.900000 0.010000 6.910000 ( 6.924297) robert inject 6.560000 0.000000 6.560000 ( 6.588160) robert inject rescue 6.080000 0.010000 6.090000 ( 6.094140) ---------------------------------------------- total: 59.530000sec user system total real original 10.450000 0.010000 10.460000 ( 10.467971) original clean 11.490000 0.030000 11.520000 ( 11.600672) vince 5.210000 0.000000 5.210000 ( 5.219863) william 12.820000 0.010000 12.830000 ( 12.839722) daniel 6.930000 0.010000 6.940000 ( 6.945329) robert inject 6.580000 0.010000 6.590000 ( 6.591095) robert inject rescue 6.080000 0.000000 6.080000 ( 6.117226) --Apple-Mail-2-287622042 Content-Transfer-Encoding: 7bit Content-Type: text/x-ruby-script; x-unix-mode=0644; name=bm.rb Content-Disposition: attachment; filename=bm.rb require 'benchmark' N = 500_000 hash = { "index" => "list", ["edit", "update"] => "manage_one", ["new", "create", "destroy"] => "manage_all" } Benchmark.bmbm do |bm| bm.report 'original' do N.times do Hash[*hash.to_a.collect{|x| Array === x[0] ? x[0].zip([x[1]]*x[0].size) : x }.flatten] end end bm.report 'original clean' do N.times do Hash[*hash.inject([]){|arr, (k, v)| arr += Array === k ? k.zip([v]* k.size) : [k, v] }.flatten] end end bm.report 'vince' do N.times do h = {} for k,v in hash [*k].each {|l| h[l] = v} end end end bm.report 'william' do N.times do Hash[ *hash.map{|k,v| k=[*k]; k.zip([v]*k.size) }.flatten ] end end bm.report 'daniel' do N.times do h={};hash.map{|k,v|[*k].map{|t|h[t]=v}} end end bm.report 'robert inject' do N.times do hash.inject({}){|h,(k,v)| k.to_a.each {|x| h[x]=v};h} end end bm.report 'robert inject rescue' do N.times do hash.inject({}){|h,(k,v)| k.each {|x| h[x]=v} rescue h[k]=v;h} end end end --Apple-Mail-2-287622042 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; format=flowed -- Eric Hodel - drbrain@segment7.net - http://blog.segment7.net I LIT YOUR GEM ON FIRE! --Apple-Mail-2-287622042--