DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Ruby Dice Roller
Just a brief exercise, I couldn't find anything on DZone Snippets that did this in Ruby. I wanted some pretty formatting, too, so it could be simplified.
class Fixnum
def roll(num=1)
out = Hash.new{|h,k| h[k] = []}
num.times {
out[:rolls] << 1 + rand(self)
}
out[:total] = out[:rolls].inject{|sum,n| sum + n}
out
end
end
Usage would be:
>> 6.roll 4
=> {:rolls=>[5, 6, 5, 5], :total=>21}
Next step would be to make it more #d# format, so 3.d(20) would work, and would be dead simple to implement.
class Fixnum
def d(sides=2)
out = Hash.new{|h,k| h[k] = []}
self.times {
out[:rolls] << 1 + rand(sides)
}
out[:total] = out[:rolls].inject{|sum,n| sum + n}
out
end
end
>> 3.d(6)
=> {:rolls=>[4, 5, 4], :total=>13}
Et voila!




