Hi --

On Mon, 5 Oct 2009, Jim Burgess wrote:

> Hi,
>
> I need to count the number of times an element occurs in an array.

*** DISCLAIMER ***

This answer is just for fun, and because sometimes seeing useful
techniques in strange contexts helps people learn and remember them.

With that in mind... here's a

>> strings = %w{a b a a c b b b c c c d }
=> ["a", "b", "a", "a", "c", "b", "b", "b", "c", "c", "c", "d"]
>> hash = Hash.new {|h,k| [k, strings.count(k)] }
=> {}
>> hash.values_at(*strings.uniq)
=> [["a", 3], ["b", 4], ["c", 4], ["d", 1]]

It's not really a good way to count array elements, but it's kind of
an interesting illustration of some hash semantics.


David

-- 
David A. Black, Director
Ruby Power and Light, LLC (http://www.rubypal.com)
Ruby/Rails training, consulting, mentoring, code review
Book: The Well-Grounded Rubyist (http://www.manning.com/black2)