From: "David A. Black" Date: 2008-04-26T23:53:10+09:00 Subject: Re: All occurances of a character in a string Hi -- On Sat, 26 Apr 2008, Raghu Go wrote: > Hi - I am trying to figure out the ruby way of printing all occurances > of a character in a string.. > > The index method on string gives only the first occurance only. > > Example input string - abbccdaab > desired output - 'a' = 0 6 7 > 'b' = 1 2 8 > 'c' = 3 4 > 'd' = 5 > > Any help greatly appreciated.. I have this really strong feeling that there's a really easy way, but I can't think of it or find it. Meanwhile, if you're using 1.9 you could do something like: str = "abcdbcdae" h = Hash.new {|h,k| h[k] = [] } str.each_char.map.with_index {|char, i| h[char] << i } which would put a hash of results in h. I just have this hunch that there was a way to accumulate offsets from a scan or gsub operation, but I can't come up with it. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!