carolineartz
1/20/2014 - 2:36 AM

Implement a basic Die class which can be initialized with some number of sides. We can then roll the die, returning a random number. It shou

Implement a basic Die class which can be initialized with some number of sides. We can then roll the die, returning a random number. It should work like this:

die = Die.new(6) die.sides # returns 6 die.roll # returns a random number between 1 and 6 If we pass Die.new a number less than 1, we should raise an ArgumentError. This is done using the raise keyword. See the ArgumentError documentation for how to do this.

Read the Kernel#rand documentation for information on how to return random numbers.

#######################################PSEUDOCODE###################################

# INPUT, OUTPUT & PSEUDOCODE:
# Initialize  =>      INPUT: number of sides = integer > 0
#                     OUTPUT: new Die object
#                     # set instance variable sides to value of passed argument
# Die#sides   =>      INPUT: none
#                     OUTPUT: number of sides
                      # getter/accessor method for sides
# Die#roll    =>      INPUT: none
#                     OUTPUT: random number between 1 and constructor input
#                     # create range for by accessing @sides 
#                     # and return randomly number in range

###################################INITIAL CODE#####################################

class Die
  def initialize(sides)
    @sides = sides
    unless @sides > 0
      raise ArgumentError.new("Number of sides must be at least 1")
    end
  end

  def sides
    @sides
  end

  def roll
    rand(1..@sides)
  end
end

####################################REFACTORED CODE#################################

class Die
  attr_reader :sides

  def initialize(sides)
    raise ArgumentError.new("#{sides} sides? Really?") if sides < 1
    @sides = sides
  end

  def roll
    rand(1..@sides)
  end
end

###################################DRIVER CODE######################################

random = rand(1..30)

die = Die.new(random)
p die.sides == random
p (1..random).cover?(die.roll)

###################################REFLECTION#######################################

# ? need unit testing framework e.g., rspect, TEST::UNIT -> assert_raise 
# I wondered if Ruby's attr_reader was literally an alias of the getter method--that it would pass the 
# rspec testing specifically for inclusion of #sides method; seems like it does...