This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this stage, we'll be working towards creating our own class that uses blocks, arrays, hashes, and more. In this video, we'll print out a scoreboard of our monster's actions.
Code Samples
Here is our final Monster class:
class Monster
attr_reader :name, :actions
def initialize(name)
@name = name
@actions = {
screams: 0,
scares: 0,
runs: 0,
hides: 0
}
end
def say(&block)
print "#{name} says... "
yield
end
def print_scoreboard
puts "------------------------------"
puts "#{name} scoreboard"
puts "------------------------------"
puts "- Screams: #{actions[:screams]}"
puts "- Scares: #{actions[:scares]}"
puts "- Runs: #{actions[:runs]}"
puts "- Hides: #{actions[:hides]}"
puts "------------------------------"
end
def scream(&block)
actions[:screams] += 1
print "#{name} screams! "
yield
end
def scare(&block)
actions[:scares] += 1
print "#{name} scares you! "
yield
end
def run(&block)
actions[:runs] += 1
print "#{name} runs! "
yield
end
def hide(&block)
actions[:hides] += 1
print "#{name} hides! "
yield
end
end
And here is how we can use it:
monster = Monster.new("Fluffy")
monster.say { puts "Welcome to my home." }
monster.scream do
puts "BOO!"
end
monster.scare do
puts "Go away!"
end
monster.run do
puts "Going to get you!"
end
monster.hide do
puts "Running away and hiding!"
end
puts "\n"
monster.print_scoreboard
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up