From: Robert Klemme Date: 2007-11-28T01:53:22+09:00 Subject: Re: Most elegant way to do this? 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 ;-) robert -- use.inject do |as, often| as.you_can - without end