From: twifkak@... Date: 2005-07-20T04:04:20+09:00 Subject: Re: Regarding rand 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 >