From: Ben Stephens Date: 2005-07-20T05:03:55+09:00 Subject: Re: Regarding rand Thanks guys, Daniel, I started out with something similar to that, although yours is alot better, but then thought it would be nice to have something like random 'a'..'z' aswell or even random Thing.new(1)..Thing.new(6) . Which i'll probably not need anyway so i'll 'borrow' yours if I may. Jacob, I'm new to Ruby but seeing code like that fills me with a feeling of well-being. Devin, thanks, 1) will do!, i'm going to go and have a look at the pickaxe to see why. 2) I was vaguely aware that creating the arrays could be a bad idea for big ranges but couldn't work out how to get the nth member of a range except by doing something like value = range.first for 1..n value = value.succ end which seemed a bit nasty or by getting the entries which seemed quite nice in light of the chapter I read about duck typing Ben (Ruby Newbie) On 7/19/05, twifkak@comcast.net wrote: > I like it! Two notes: > > 1. Use #respond_to? instead of ::method_defined? This allows for singleton methods.* > > 2. What other people are saying about the cost of creating an array each time. You might use each_with_index (which is stupidly slow for Arrays), or might implement a different rand method for Range, Array, etc. > > Devin > > > I was reading Learn to Program by Chris Pine yesterday, in one bit it says: > > ' Note that I used rand(101) to get back numbers from 0 to 100, and > > that rand(1) always gives back 0.' > > > > I was wondering if rand() could support syntax like: > > rand(0..100) > > > > Here's my go: > > > > def random(value) > > if value.class.method_defined? 'entries' > > entries = value.entries > > entries[rand(entries.length)] > > else > > rand(value) > > end > > end > > > > this works with arrays and hashes too. > > > > I'm coming to Ruby via RoR and i'm loving it, I should be writing a > > web app and i'm playing with Ruby instead. > > > > Ben > > > > > >