From: repeater Date: 2002-04-03T18:20:27+09:00 Subject: RE: rcr > -----Original Message----- > From: Paul Duncan [mailto:pabs@pablotron.org] > Sent: 03 April 2002 06:26 > To: ruby-talk ML > Subject: Re: rcr > > * repeater (repeater@lucentprimate.cjb.net) wrote: > > i've not used ruby for that long, but i've found the need to do the > > following rather often: > > > > [3, 2, 5, 2, 19].rand_item # => returns random item from array > > > > short code, but could be helpful to others (needed it in all of my last > > projects, but perhaps i'm just strange) > > Were you asking for code to return a random element, or saying you have > code that returns a random element? If it's the latter, here's a > quick answer: > > -- > class Array > def rand > raise RuntimeError, 'Array#rand(): empty array' unless length > 0 > at Kernel::rand(length).floor > end > end > > # test Array#rand() > arr = %w(asdf hey matz ruby rocks test 123) > 4.times { puts arr.rand } > [].rand > -- > > produces (for this particular run): > hey > matz > rocks > hey > ./array_random.rb:5:in `rand': Array#rand(): empty array (RuntimeError) > from ./array_random.rb:15 > thanks, i've got code but forgot to post it (though i learnt a few things from yours !) is this too specialised for a RCR ? hopefully people will not consider it equally silly as retreiving an item according to a digit of Pi (therefore: "write your own arr.pi_item, damnit!"). i would expect if to be part of Array, and i needed it suspiciously often the last few weeks. perhaps i'm a bit hasty, basing my request on my limited experience :-) so my apologies if this is so regards repeater