From: Tim Hunter Date: 2009-02-11T07:09:27+09:00 Subject: Re: Counting Occurrences of a String in an Array shrouded.shoyu@gmail.com wrote: > Hi, > > I'm pretty new to Ruby, and I've been trying to figure out the best > way to do this with little luck. > > I have an array that is all strings, and I need to count, for each > string in the array, how many times some substring appears in it. > > So, for example, my array is ["aaa", "aab", "abb", "bbb"] and I want > to return a new array that tells me how many times "a" appears: [3, 2, > 1, 0] > > Can anyone point me in the right direction with this? > > Thanks! > > Looks like a job for collect: irb(main):008:0> a = ["aaa", "aab", "abb", "bbb"] => ["aaa", "aab", "abb", "bbb"] irb(main):009:0> a.collect {|v| v.scan(/a/).size} => [3, 2, 1, 0] -- RMagick: http://rmagick.rubyforge.org/