Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news-1.dfn.de!news.dfn.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Making a count of unique elements in an array Date: Sat, 28 Dec 2013 12:02:41 +0100 Lines: 21 Message-ID: References: <1136789236.482098.144200@o13g2000cwo.googlegroups.com> <5327790f-e3da-4cb6-a94c-b198de7139da@googlegroups.com> <9d904cf9-f46c-4ec9-8564-45614ff97501@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net rJZyZM/Ijy2VIZtNf7dW+AXb882HRr1LYKN81cRV0vsm1zAxY= Cancel-Lock: sha1:GChFnkpkb2MJWq8tt3Tmdtknby0= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Thunderbird/24.2.0 In-Reply-To: <9d904cf9-f46c-4ec9-8564-45614ff97501@googlegroups.com> Xref: csiph.com comp.lang.ruby:6907 On 26.12.2013 22:44, lukeabergen@gmail.com wrote: > Another way is the super-useful group_by and map > > arr = ["a", "b", "b", "c", "c", "d", "e", "e", "e"] > grouped = arr.group_by {|x| x} #=> produces something like {"a" => ["a"], "b" => ["b", "b"], etc... > result = grouped.map {|el, arr| [el, arr.count]} Downside of that approach is that it does unnecessary work and uses more memory than necessary. And the result is not a Hash which may make retrieval of the counts of an element quite expensive if there are many different values. Btw, the OP spoke of a "2D array". So the input likely looks different than in your example. We also do not know what he actually wants to count. Is it individual elements? Or does "distinct elements" refer to a single array? Kind regards robert