File: rubydice.rb

Project: Invitation to Ruby

#!/usr/bin/env ruby

class StandardDice
  def toss
    @top = rand(6) + 1
  end
  def top
    @top
  end
end

class CoinOperatedDice
  attr_reader :top
  def toss
    @top = 1
    5.times {
      @top += 1 if rand(2) == 0
    }
  end
end

class DiceUser
  SIDES = 6
  WIDTH = 35
  THROWS= 10000
  AVG_WIDTH = THROWS/SIDES

  def examine(dice)
    @bins = [0, 0, 0, 0, 0, 0]
    THROWS.times {
      dice.toss
      @bins[dice.top-1] += 1
    }
  end

  def histogram
    @bins.each_with_index { |value, index|
      printf "%1d [%04d]: %s\n",
	index+1, value, bar(value)
    }
  end

  def bar(n)
    stars = "*" * (n * WIDTH / AVG_WIDTH)
  end
end

def use_dice(d)
  d.toss
  puts "The top of the die is #{d.top}"
end

def histograms
  user = DiceUser.new
  user.examine(StandardDice.new)
  puts "Six Sided Dice"
  user.histogram
  puts ""
  puts "Coin Operated Dice"
  user.examine(CoinOperatedDice.new)
  user.histogram
end

if __FILE__ == $0 then
  histograms
end


[ Index ][ Table of Contents ]
Generated by [ source2html ]