From: Robert Klemme Date: 2007-11-28T04:35:02+09:00 Subject: Re: Most elegant way to do this? On 27.11.2007 20:24, Brian Adkins wrote: > On Nov 27, 11:53 am, Robert Klemme wrote: >> 2007/11/27, Brian Adkins : >> >> >> >>> On Nov 26, 7:17 pm, rbysam...@gmail.com wrote: >>>> Are there any more elegant, concise, pithy, and more Rubyish ways of >>>> doing this? >>>> def roll(number_of_dice) >>>> sum = 0 >>>> number_of_dice.times do >>>> sum += rand(5).next >>>> end >>>> sum >>>> end >>>> Thanks in advance! >>> As others have pointed out, you need rand(6).next to get (1..6); >>> otherwise, it's hard to improve on what you have here. This is a >>> simple, iterative mathematical function. I personally don't think >>> using map, inject, etc. is more "Rubyish" in this context, just 2 to 3 >>> times slower. >>> The interface is "roll n" regardless of the underlying implementation, >>> so you might as well make it fast. >>> One style improvement might be to use a one line block: >>> def roll num_dice >>> sum = 0 >>> num_dice.times { sum += rand(6).next } >>> sum >>> end >>> You can make it ~10% faster (with the loss of some readability) by not >>> invoking next each time and just summing at the end: >>> def roll num_dice >>> sum = 0 >>> num_dice.times { sum += rand(6) } >>> sum + num_dice >>> end >> I guess there is even more room for improvement by doing this: >> >> def roll num_dice >> sum = roll num_dice >> num_dice.times { sum += rand(6) } >> sum >> end >> >> SCNR ;-) > > No apology necessary, I beat you to it :) (I assume you meant sum = > num_dice) Yes, of course. Copy & paste... Cheers robert