From: Charles Oliver Nutter Date: 2008-08-01T08:33:15+09:00 Subject: [ruby-core:18036] Re: New array methods cycle, choice, shuffle (plus bug in cycle) Restarting this thread because I missed it the first time around and because I agree it should be "choose" rather than "choice" if it's going to be in. Also, it doesn't appear to have been settled the first time. choice is a noun. choose, map, select, collect, etc are imperative verbs. So choose much more consistent with the others. Also, choice implies to me that it's already been made...since you can't have a choice unless you've already made a "choice". In essence, a "choice" is the product of "choosing" something. So ary.choose produces a choice. - Charlie David Flanagan wrote: > Four new methods have been added to Array the Ruby 1.9 trunk. I've got > a couple of questions and comments and one bug report: > > cycle is an iterator that is like calling each on the array within an > infinite loop. Matz: have you considered generalizing this to be a > method of Enumerable? > > cycle has what I'd consider a bug: call it on an empty array and it will > never return and will never invoke the associated block. > > ruby1.9 -e '[].cycle {}' > > When I do this I can't even ^C to stop ruby. I have to kill -9 the > process. I'd suggest that cycle simply return when the array is empty. > That is, it cycles until the array becomes empty (which will be forever > in most cases). The patch I propose is at the bottom of this message. > > choice returns a random element from the array. I don't like the name > of this method: neither the word "choice" nor it verb form "choose" > imply randomness--instead they suggest the opposite. I suggest just > using the name "rand", "random" or "random_element". Most array methods > are verbs, but a noun here would match the existing methods first and > last. Also, may I suggest a random! variant of the method that returns > *and removes* a random element from the array? first and last already > have shift and pop to serve this purpose. > > shuffle and shuffle! randomly permute an array and seem worth having. I > think I remember Josh Bloch (author of the Java collections library) > writing somewhere that shuffling an array correctly is actually kind of > hard to do, so I think it is great to have these methods, even if I > can't think of a use case right now :-) > > David > > --- array.c.orig 2007-09-06 15:00:02.000000000 -0700 > +++ array.c 2007-09-06 15:03:30.000000000 -0700 > @@ -2940,6 +2940,7 @@ > > RETURN_ENUMERATOR(ary, 0, 0); > for (;;) { > + if (RARRAY_LEN(ary) == 0) return Qnil; > for (i=0; i rb_yield(RARRAY_PTR(ary)[i]); > } > >