Hi --

On Wed, 3 Apr 2002, Tobias Reif wrote:

> Paul Duncan wrote:
>
>
> > class Array
> >   def rand
> >     raise RuntimeError, 'Array#rand(): empty array' unless length > 0
> >     at Kernel::rand(length).floor
> >   end
> > end
>
>
> or
>
> class Array
>    def any
>      if empty?
>        nil
>      else
>        self[rand length]
>      end
>    end
> end
>
> random_character = ('a'..'z').to_a.any
>
> puts random_character

Aw, heck, let's go nuts :-)

  module Enumerable
    def any
      a = to_a
      a.at(rand a.size)
    end
  end

  r = ('a'..'z').any
  puts r


My reason for getting rid of the nil test is that the thing will
return nil anyway if the array is empty.  If you wanted to
distinguish the empty case from, say, the middle element of
[1,2,nil,3,4], I guess you'd have to raise an exception, as in
Paul's code.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav