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

Dice in Ruby (cont)

What would our coin operated version of dice look like?

  1: class CoinOperatedDice
  2:   attr_reader :top
  3:   def toss
  4:     @top = 1
  5:     5.times {
  6:       @top += 1 if rand(2) == 0
  7:     }
  8:   end
  9: end

  • [1] Introduce the class CoinOperatedDice
  • [2] Writing functions to return (or set) the value of an attribute is a rather common exercise, so Ruby provides a shortcut for this. Line 2 is identical to writing ...

            def top
              @top
            end

  • [5] times is another method that takes a block. When times is sent to an integer, the block is executed that many times.
  • [6] We increment the value of @top if the random number returned from rand(2) is equal to 0. Since the number will be either 0 or 1, we will increment @top about half the time.


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