From: "Peña, Botp" Date: 2008-03-04T12:06:18+09:00 Subject: Re: Split the string From: Christopher Swasey [mailto:christopher.swasey@gmail.com] # On 3/3/08, Michael Fellinger wrote: # > require 'scanf' # > "3:43;SD,2:65;SD,3:50;Inc".split(',').map do |e| # > e.scanf('%d:%d;%s') # > end # > # [[3, 43, "SD"], [2, 65, "SD"], [3, 50, "Inc"]] # > # > ^ manveru # # We have a winner! # careful, you might want to benchmark that, too. a sample run on a windows machine, C:\Documents and Settings\botp>cat test.rb require 'benchmark' require 'enumerator' require 'scanf' n=1_000 s="3:43;SD,2:65;SD,3:50;Inc" puts RUBY_VERSION,RUBY_PLATFORM Benchmark.bmbm do |x| x.report("scan") do n.times do s.scan(/(\d+):(\d+);(\w+)/).map do |x| [x[0].to_i,x[1].to_i,x[2]] e end end x.report("slice") do n.times do a=[] s.split(/,|:|;/).each_slice(3){|x| a << [x[0].to_i,x[1].to_i,x[2]]} end end x.report("split2") do n.times do s.split(/,/).map do |i| t = i.split(/:|;/) t[0..1].map { |j| j.to_i } << t[2] end end end x.report("scanf") do n.times do s.split(',').map do |e| e.scanf('%d:%d;%s') end end end end C:\Documents and Settings\peñaijm>ruby test.rb 1.8.6 i386-mswin32 Rehearsal ------------------------------------------ scan 0.063000 0.000000 0.063000 ( 0.063000) slice 0.078000 0.000000 0.078000 ( 0.079000) split2 0.109000 0.000000 0.109000 ( 0.110000) scanf 2.938000 0.015000 2.953000 ( 3.188000) --------------------------------- total: 3.203000sec user system total real scan 0.063000 0.000000 0.063000 ( 0.063000) slice 0.093000 0.000000 0.093000 ( 0.094000) split2 0.125000 0.000000 0.125000 ( 0.125000) scanf 2.984000 0.032000 3.016000 ( 3.031000) kind regards -botp