Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic 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 create the shell class that will hold our monster.
Code Samples
class Monster
attr_reader :name
def initialize(name)
@name = name
end
end
Here's how we can initialize it:
monster = Monster.new("Fluffy")
-
0:00
[MUSIC]
-
0:04
So far, we've learned about blocks in Ruby and how powerful they are.
-
0:09
Now we're going to put all of that knowledge to the test and
-
0:12
write a program using work spaces.
-
0:14
We'll be working with Ruby's built in classes, writing our own classes and
-
0:18
methods, and practicing with blocks.
-
0:21
So let's go ahead and get started.
-
0:23
Okay, so let's go ahead and create our own class that uses blocks and
-
0:28
hashes and strings and everything we've learned so far.
-
0:32
What we're going to do is make a class for a monster.
-
0:36
And a monster is going to be able to do a few different things.
-
0:40
And we will do these things using blocks.
-
0:43
So, let's go ahead and create monster.rb.
-
0:47
So, first step is to define the class.
-
0:53
And the class is Monster.
-
0:57
We're going to go ahead and
-
0:58
give the monster a name when we initialize the class.
-
1:05
And, let's go ahead and just set that to an instance variable.
-
1:10
And make an attr_reader out of that so
-
1:13
we don't have to type the at sign inside of the class.
-
1:20
So, first thing that we'll do?
-
1:23
Let's go ahead and make the monster say something.
-
1:32
And the monster will say something, and then execute whatever is in the block.
-
1:37
We're going to assume that when somebody calls this,
-
1:42
they are going to be printing something to the screen.
-
1:45
So we'll just go ahead and print the name says, so
-
1:51
that would be the name of the monster, and the word says.
-
1:56
So let's go ahead and create a new monster here.
-
1:59
And we'll give this monster a very intimidating monster-like name.
-
2:06
Fluffy.
-
2:07
And, the monster will say.
-
2:13
What's the monster gonna say?
-
2:15
What's something scary that a monster would say?
-
2:19
Welcome to my home.
-
2:24
Let's go ahead and save that.
-
2:26
And run it.
-
2:30
Oh, nothing happened.
-
2:31
Why?
-
2:33
Because we didn't call the block or yield to it.
-
2:37
So let's go ahead and yield, and run this again.
-
2:44
So there we go, Fluffy says...
-
2:45
Welcome to my home.
-
2:47
And that's a pretty good start.
-
2:49
So let's go ahead and start implementing some more actions in the next video.
You need to sign up for Treehouse in order to download course files.
Sign up