[ next ] [ prev ] [ contents ] [ up to Appendix A -- What is Object Oriented? ] Invitation To Ruby

Dice in Ruby (cont)

  1: class DiceUser
  2:   SIDES = 6
  3:   WIDTH = 35
  4:   THROWS= 10000
  5:   AVG_WIDTH = THROWS/SIDES
  6: 
  7:   def examine(dice)
  8:     @bins = [0, 0, 0, 0, 0, 0]
  9:     THROWS.times {
 10:       dice.toss
 11:       @bins[dice.top-1] += 1
 12:     }
 13:   end
 14: 
 15:   def histogram
 16:     @bins.each_with_index { |value, index|
 17:       printf "%1d [%04d]: %s\n",
 18:         index+1, value, bar(value)
 19:     }
 20:   end
 21: 
 22:   def bar(n)
 23:     stars = "*" * (n * WIDTH / AVG_WIDTH)
 24:   end
 25: end

More code that uses dice objects. This one does something (moderately) interesting.

  • [2-5] Introduce some constants
  • [7-13] Throw a dice 10000 times and record the number of times each number turns up.
  • [15-20] Display a histogram of the number of times.
  • [17-18] Use printf to produce a formatted string.
  • [22-25] Print a bar for the histogram. Use asterisks to build the bar.


[ next ] [ prev ] [ contents ] [ up to Appendix A -- What is Object Oriented? ] Copyright 2002 by Jim Weirich.
All rights reserved.