Forked from dbc-challenges/phase0_week2_challenge_template.rb
Last active
January 3, 2016 20:19
-
-
Save carolineartz/5755c95fdddc8a03fc06 to your computer and use it in GitHub Desktop.
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 …
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#######################################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... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment