On Oct 5, 2009, at 02:24 , Jim Burgess wrote:

> Hi,
>
> I need to count the number of times an element occurs in an array.
>
> At the moment I'm doing it like this:
>
> a = ["a", "b", "a", "b", "b"]
> b = a.uniq
> c = []
>
> 0.upto(b.length-1) do |e|
>   d = 0
>   0.upto(a.length-1) do |f|
>      if b[e] == a[f]
>   d += 1
>      end
>   end
>   c << d
> end
>
> print b, c
>> ["a", "b"] [2, 3]

Some suggestions:

Your indentation is wack. Make sure you're not mixing spaces and tabs.  
2 spaces per indent. You're mixing 2 & 3 & possibly tabs at 8.

Your variable names are meaningless. Improve that and you'll have a  
lot better time debugging when it is 4am and you're tired.

You're not using (sensible) iterators. I suggest you read that section  
in the pickaxe book.

You're not using good data structures or algorithms. You're passing  
over the elements of 'a' (see? better names means better readability!)  
a.uniq.size times and doing a.size * a.uniq.size string equality  
comparisons.

Take a look at this:

# use a hash whose values default to 0 for proper data structure use
# use count as the name, since that's what it is storing.
count = Hash.new 0

# iterate over each string only once
strings.each do |string|
   # increment the count for each string
   count[string] += 1
end

p count

If you nuke all the comments, the code makes just as much sense (if  
not more). That's what we try to achieve in ruby whenever we can.