From: Robert Klemme Date: 2008-04-27T00:20:07+09:00 Subject: Re: All occurances of a character in a string On 26.04.2008 16:53, David A. Black wrote: > 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. In 1.8 irb(main):001:0> require 'enumerator' => true irb(main):002:0> str = "abcdbcdae" => "abcdbcdae" irb(main):003:0> ind = Hash.new {|h,k| h[k]=[]} => {} irb(main):004:0> str.to_enum(:scan,/./).each_with_index {|c,i|ind[c]< # irb(main):005:0> ind => {"a"=>[0, 7], "b"=>[1, 4], "c"=>[2, 5], "d"=>[3, 6], "e"=>[8]} > 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. Like this? irb(main):017:0> str = "abcdbcdae" => "abcdbcdae" irb(main):018:0> ind = Hash.new {|h,k| h[k]=[]} => {} irb(main):019:0> str.scan(/./) {|c| ind[c] << $`.length} => "abcdbcdae" irb(main):020:0> ind => {"a"=>[0, 7], "b"=>[1, 4], "c"=>[2, 5], "d"=>[3, 6], "e"=>[8]} Cheers robert