From: William James Date: 2005-08-13T05:36:11+09:00 Subject: Re: no clue Joe Van Dyk wrote: > On 8/12/05, William James wrote: > > Joe Van Dyk wrote: > > >I have a string like: > > > > > >"some_key: blah, some_other_key: more_blah, > > > yet_other_key: yet_more_blah" > > > > > >I want to build up a hash like > > > > > >{ :some_key => "blah", :some_other_key => "more_blah", > > > :yet_other_key => "yet_more_blah" } > > > > h={} > > DATA.read.split(/\s*[:,\n]\s*/).inject(false){|a,b| > > if a then h[a.to_sym]=b; a=false else a=b end } > > > > p h > > __END__ > > some_key: blah, some_other_key: more_blah, yet_other_key: yet_more_blah > > key1:value1 > > key2: value2 > > key3 : value 3 , key4 :value4 , key555555555:value55555 > > > > > > ---- > > Output: > > > > {:key3=>"value 3", :some_key=>"blah", :key4=>"value4", > > :some_other_key=>"more_blah", :key555555555=>"value55555", > > :yet_other_key=>"yet_more_blah", :key1=>"value1", > > :key2=>"value2"} > > Why would this approach be faster? data = []; DATA.each{|x| data << x.chomp} iter = 100_000 h={} start = Time.now iter.times { data.each{|line| line.split(/\s*[:,]\s*/).inject(false){|a,b| if a then h[a.to_sym]=b; a=false else a=b end }} } t1 = Time.now - start result_hash = {} start = Time.now iter.times { data.each{|line| line.scan(/(\w+)\s*:\s*([^, ]*)/) do |k, v| result_hash[k.to_sym] = v end } } t2 = Time.now - start p result_hash == h p t1,t2 __END__ some_key: blah, some_other_key: more_blah, yet_other_key: yet_more_blah key1:value1,key2: value2,key3 :value_3 , key4:value4,key555555555:value55555 x_position: 20, y_position: 40, z_position: 30,zz_position:85 Output: true 22.859 28.094