Last active
December 18, 2015 02:29
-
-
Save ashleygwilliams/5711370 to your computer and use it in GitHub Desktop.
how much wood would a woodchuck chuck? a lesson in the difference between class and instance variables and methods.
This file contains 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
class Woodchuck | |
attr_accessor :chuck_count | |
@@woodchuck_count = 0 | |
def initialize | |
@chuck_count = 0 | |
@@woodchuck_count += 1 | |
end | |
def self.woodchuck_count | |
@@woodchuck_count | |
end | |
def chuck_wood | |
@chuck_count += 1 | |
end | |
end | |
myWoodchucks = [] | |
chuckedWood = 0 | |
rand(10).times do | |
myWoodchucks.push(Woodchuck.new) | |
rand(10).times do | |
myWoodchucks.last.chuck_wood | |
end | |
end | |
puts "How many woodchucks?" | |
puts Woodchuck.woodchuck_count.to_s | |
#check | |
#puts myWoodchucks.length | |
puts "How much wood chucked?" | |
myWoodchucks.each do |woodchuck| | |
chuckedWood += woodchuck.chuck_count | |
end | |
puts chuckedWood | |
#check | |
#myWoodchucks.each_with_index do |woodchuck, index| | |
# puts "woodchuck##{index+1} chucked #{woodchuck.chuck_count} wood" | |
#end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment