From: Rick DeNatale Date: 2009-10-05T20:58:08+09:00 Subject: Re: Count the number of times an element occurs in an array On Mon, Oct 5, 2009 at 6:14 AM, David A. Black wrote: > 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. Or, since we don't use a key more than once one could do: strings = %w{a b a a c b b b c c c d } not_a_hash = lambda {|k| [k, strings.count(k)] } strings.uniq.map {|s| not_a_hash[s]} => [["a", 3], ["b", 4], ["c", 4], ["d", 1]] -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale