[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Array#group_by

Bruno Michel

11/29/2006 3:17:00 PM

Gareth Adams a écrit :
> I posted this on the Rails list, but then I realised it would make more sense
> over here:
>
> -------
>
> Just thought I'd share a function which has been really useful to me, for 2
> reasons
>
> 1) It could easily help someone else
> 2) People might be able to make it work better or point out where it's not
> optimal
>
> class Array
> # Groups elements of an array based on a user-defined condition
> #
> # Each element from this array is passed to the block, and the returned value
> # determines the key under which it will be stored in the output hash
> #
> # If no block is given then the array indices will be used as the hash keys
> def group_by
> hsh = {}
> self.dup.each_with_index do |element, i|
> if block_given?
> key = yield element
> else
> key = i
> end
> hsh[key] ||= []
> hsh[key] << element
> end
> hsh
> end
> end


Hi,

thanks for the tip. I have q question with do you use a ".dup" on the
line self.dup.each_with_index do |element, i| ? Facets has a similar
function (partition_by), but don't use a ".dup" before iterating:

http://facets.rubyforge.org/api/core/classes/Enumerable.ht...

--
Bruno Michel

5 Answers

Ara.T.Howard

11/29/2006 3:25:00 PM

0

Louis J Scoras

11/29/2006 5:15:00 PM

0

If you don't care about duplicates, just use Set#classify.


--
Lou.

Joel VanderWerf

11/29/2006 11:54:00 PM

0

Louis J Scoras wrote:
> If you don't care about duplicates, just use Set#classify.

Why isn't there an Array#classify, which would return a hash of arrays,
preserving duplicates?

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Louis J Scoras

11/30/2006 12:49:00 AM

0

On 11/29/06, Joel VanderWerf <vjoel@path.berkeley.edu> wrote:

> Why isn't there an Array#classify, which would return a hash of arrays,
> preserving duplicates?

Beats me =) I'm not arguing against such a method; just pointing out
that there's already something that might get the job done. A lot of
times people use arrays to represent sets without realizing it.


--
Lou.

Joel VanderWerf

11/30/2006 3:50:00 AM

0

Louis J Scoras wrote:
> On 11/29/06, Joel VanderWerf <vjoel@path.berkeley.edu> wrote:
>
>> Why isn't there an Array#classify, which would return a hash of arrays,
>> preserving duplicates?
>
> Beats me =) I'm not arguing against such a method; just pointing out
> that there's already something that might get the job done. A lot of
> times people use arrays to represent sets without realizing it.

I wasn't arguing either. I had forgotten about the useful Set#classify,
and thought why not have one for Array too? I can't see any theoretical
reason not to.

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407