On Mon, Dec 15, 2008 at 5:31 PM, Stuart Clarke
<stuart.clarke1986 / gmail.com> wrote:
> I am reading delimited lines of data stored in array eg
>
> 123   name     address      date       product
>
> I perform an array.each and then run an if statement based on the ID
> (123). What I wish to do now is say
>
> if you find ID 123
> read the entries in name and count unique names
>
> eg the entries bob bob mike sue
> Would report 2      bob
>             1      mike
>             1      sue
>
> I was thinking something like this
>
> if id==123
>  namelist.push name
>  counts = Hash.new(0)
>  if namelist.find {|n| (counts[n]) +=1}
>    puts counts + name
>
> Obviously the coding is not correct, but can anyone comment or expand
> further on this?

An approach...

a = %w(bob bob mike sue)
p a.inject(Hash.new(0)) {|h, n| h[n] += 1; h}
=> {"mike"=>1, "sue"=>1, "bob"=>2}

...or (in 1.8.7) a different one...

a = %w(bob bob mike sue)
p a.uniq.inject({}) {|h, i| h[i] = a.count(i); h}

Todd