File: rubydice_doc.rb

Project: Invitation to Ruby

#!/usr/bin/env ruby

# The standard dice class implements a regular six-sided dice.
class StandardDice
  # Toss the dice to get a new value on top.
  def toss
    @top = rand(6) + 1
  end

  # Report the value of the top of the dice.
  def top
    @top
  end
end

# Another dice-like class, but with a completely different
# implementation.  
class CoinOperatedDice
  # Report the top value of the dice.
  attr_reader :top

  # Toss the dice to get a new value on top.
  def toss
    @top = 1
    5.times {
      @top += 1 if rand(2) == 0
    }
  end
end


# Determine the statistical randomness of a dice-like object.  
class DiceUser
  SIDES = 6
  WIDTH = 35
  THROWS= 10000
  AVG_WIDTH = THROWS/SIDES

  # Examine the dice to be able to generate the histograms.
  def examine(dice)
    @bins = [0, 0, 0, 0, 0, 0]
    THROWS.times {
      dice.toss
      @bins[dice.top-1] += 1
    }
  end

  # Display the histograms of the most recently examined dice object.
  def histogram
    @bins.each_with_index { |value, index|
      printf "%1d [%04d]: %s\n",
	index+1, value, bar(value)
    }
  end

  # Generate a histogram bar (of asterisks) for a value of _n_.  Scale
  # to fit in the desired columns.
  def bar(n)
    stars = "*" * (n * WIDTH / AVG_WIDTH)
  end
end

# Simple example of function using a dice object.
def use_dice(d)
  d.toss
  puts "The top of the die is #{d.top}"
end

# Generate the histograms for a standard six-sided dice object and a
# coin operated one.
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

# Run the main program
if __FILE__ == $0 then
  histograms
end


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