From: Adam Shelly Date: 2008-05-01T04:02:58+09:00 Subject: Re: All occurances of a character in a string > On Sat, Apr 26, 2008 at 9:55 PM, 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. I thought of the 'indexes' method, but that works in reverse. So I made my own version: class Array def all_indexes val (0..length).map{|i|self[i]==val ? i : nil}.compact end alias :all_indicies :all_indexes end p 'hello world'.split('').all_indicies('l') => [2, 3, 9] > > > > Example input string - abbccdaab > > desired output - 'a' = 0 6 7 > > 'b' = 1 2 8 > > 'c' = 3 4 > > 'd' = 5 > > > > Any help greatly appreciated.. Source = 'abbccdaab' s=Source.split('') s.uniq.each{|v| puts "'#{v}' = #{s.all_indexes(v)*' '}"} => 'a' = 0 6 7 'b' = 1 2 8 'c' = 3 4 'd' = 5 -Adam