From: Raghu Go Date: 2008-04-26T23:37:26+09:00 Subject: Re: All occurances of a character in a string I did a quick test and like Siep's modifications.. Method1 Time elapsed: 0.236999988555908 milliseconds Siep's modification Method2 Time elapsed: 0.123999834060669 milliseconds def method1(a) i = 0 ret = Hash.new a.scan(/./) {|c| ret[c] = ret[c].nil? ? [i] : ret[c] << i i = i + 1 } p a p ret end def method2(str) #Siep ar = str.split("") result = Hash.new{Array.new} ar.each_with_index do|item,index| result[item] = result[item]< S2 wrote: >> S2 wrote: >> >>> irb(main):006:1> ret[c] = ret[c].nil? ? d : d << ret[c] >>> irb(main):007:1> ret[c].flatten! >> >> oh sorry, here are a few things that are not needed: >> a = "abbccdaab" >> i = 0 >> ret = Hash.new >> a.scan(/./) {|c| >> ret[c] = ret[c].nil? ? [i] : ret[c] << i >> i = i + 1 >> } >> p a >> p ret > > The block form of Hash.new gets rid of the if-statement; like this: > > str = "abbccdaab" > ar = str.split("") > result = Hash.new{Array.new} > > ar.each_with_index do|item,index| > result[item] = result[item]< end > > result.each{|k,v| puts k + " = " + v.join(",")} > > regards, > > Siep -- Posted via http://www.ruby-forum.com/.