Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ruby Dice Roller Plus!

DZone's Guide to

Ruby Dice Roller Plus!

·
Free Resource
So you are happy with the original Ruby Dice roller, but wish you could combine dice rolls or add bonuses just like you might in D&D?

Well wish no more!


class Dicer
  attr_accessor :rolls, :total, :bonus

  def initialize
    @rolls = []
    @total = 0
    @bonus = 0
  end

  def +(bonus)
    if bonus.instance_of?(Fixnum)
      @bonus += bonus
      @total += bonus
    else
      @rolls += bonus.rolls
      @total += bonus.total
      @bonus += bonus.total
    end
    self
  end
end

class Fixnum

  def d(sides=2)
    out = Dicer.new{|h,k| h[k] = []}
    self.times {
      out.rolls << 1 + rand(sides)
    }
    out.total = out.rolls.inject{|sum,n| sum + n}
    out
  end

end



Usage:

>> d = Dicer.new
=> #
  
   
>> 3.d(6)
=> #
   
    
>> 3.d(6)+1
=> #
    
     
>> 3.d(6)+2+1.d(4)
=> #
     

     
    
   
  
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}