Enter your Sign on user name and password.

Forgot password?
Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to Ruby
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for Educator.com

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Classes: Part I

  • A class defines a set of methods that an object responds to
  • It is a container that holds properties such as variables, constants, and methods
  • It can be reused through inheritance and extended or subclassed to other classes
  • Every object is an instance of a class
  • The class keyword will create a class in Ruby
  • It is delimited with an end
  • new will create a new instance of a class
  • initialize method is invoked automatically with new is called
  • self is an instance of the class
  • Accessor methods return the value of the variable
  • Setter methods also known as mutator methods sets the field to a value specified by the argument
  • Ruby provides methods to automate getter and setter methods
  • These methods are defined in the Module class and can be invoked inside any class definition

Classes: Part I

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Classes 0:10
    • Definition of a class
    • Class represents a container
    • Can be reused
  • Creating our First Class 1:00
    • Keyword class will create new class
    • Name must begin with capital letter
  • Instantiating Our First Class 2:46
    • New will create a new instance of class
  • Initializing Values 3:58
    • Definition of def
    • Instance method
    • Example
  • Defining the to_s Method 8:24
    • Creating a string representation class
    • Example
  • Self in the Class 12:16
    • Definition of self
    • Example
  • Accessor Methods 15:52
    • getter methods
    • Example
  • Setter Methods 18:00
    • Mutator methods
    • Example
  • Automating Getter and Setter Methods 21:10
    • Defined in the module class
    • attr_reader
    • attr_writer
    • attr creates getter and setter methods
    • Example
  • Notes on Ruby's Accessor Methods 25:32

Transcription: Classes: Part I

Welcome back to Educator.com.0000

Today's lesson is on classes; this is Part 1.0002

First, what is a class? A class defines a set of methods that an object responds to.0008

It represents a container that holds properties, such as variables and constants.0018

We do this to encapsulate a lot of different variables, objects, methods...and that is why we say it represents a container.0025

It can be reused; you can reuse it through inheritance, and you can extend it or subclass other classes.0038

Every object is an instance of a class.0048

First, we want to create our first class.0058

To do this, we use the class keyword; that will create a new class in Ruby.0063

Also, this creates a constant, too; this creates a new constant that refers to that class.0077

Whatever name you give after class is the constant name and the name of the class.0082

The name must begin with a capital letter; that is very important.0089

If you look at this class here--we have HelloWorld--notice that the first letter is capitalized.0093

After that, it doesn't matter what the next letters after it are: they could be lowercase or uppercase.0100

To end that class--we have our class here, HelloWorld--to end it, we just put the end at the end; that is the delimiter.0107

You can also use other things for HelloWorld; notice, we have our capital H here, but we also capitalize the subsequent word.0117

For our second word, we also have it capitalized, but we also have it lowercased, and you can also go wild and put the whole thing as uppercase.0131

Now, the convention is to, every time you have a new word, capitalize that letter, so it uses that to separate everything.0142

That is why you see, for our HelloWorld here, we have the W uppercased, as well.0153

Let's look at instantiating our first class.0161

Here I have HelloWorld.new, and it's creating its new object, and it's going to create that reference into this variable, just called hw.0167

That new will create a new instance of our class.0178

Of course, it's always like this: n-e-w, all lowercase.0183

That will actually create our class into memory.0190

After this, you can do a couple of things: I can call the class method, and it will tell me the class it's part of.0196

If I take my variable hw, and I call a .class on it, it will return to me, "This is part of the HelloWorld class."0204

I can also ask it, "Is it...?" one of these classes; so, using the the is_a? method, I can say, "Is it a class called HelloWorld?"0214

If I do that here, it's going to return true, since that is what we instantiated it as.0226

Next, let's look at initializing values.0237

To do this...instead of using function, which you often see in other languages, they often use what is called define.0242

They use def--all just in lowercase, d-e-f, and this defines an instance method for the class.0252

Like I said, in other languages you might see this as similar to the function, and then you would have your name of it here.0263

The initialize method is invoked automatically when new is called.0275

So, as you saw in that previous class, we called new to it, but you don't actually define any method in your class called new; you actually define it as initialize.0280

Speaking of that in your class, when you are creating it, it would just be def, and then initialize.0293

That creates this method that creates your object.0307

This is an instance method; it is a method that is invoked on an instance of the class.0314

So, whatever subsequent methods you make from this, they will be instance methods that are part of this class.0322

Now, this Initialize class is kind of interesting, because the new is actually a class method, but initialize is an instance method in this case, because you are defining it in this structure.0328

Let's look at an example here.0341

I have this class called HelloWorld; in it, we have our def, which says, "This defines an instance method of the class," so we have our instance method initialize.0344

It takes one parameter; it's taking a name.0359

What you see here is, it says we have this new variable that says @name, which is the instance variable, and this is getting the same value as that parameter.0363

So, as I do here, I created my class here; I instantiated the class.0378

We also initialized the name value.0393

And see here, I have HelloWorld.new, and I pass in the parameter Justin, which is the name value.0409

As I said before, we are initializing these values; what is happening here--first, we have the initialize method; it is automatically made private; if I were to do HelloWorld.new, and then I call the .initialize method, it wouldn't allow me to access it, because it's private.0423

The initialize method is accessible inside the scope of class, and you can call it as initialize, but otherwise--if I call it outside that scope--it's not going to allow me to do it.0445

It's automatically made private; the parameter is stored in local variable name.0456

Here we have this parameter name; that is the local variable.0463

Then, the name is assigned to instance variable @name.0468

We have our instance variable here...this is our instance variable, and this is our local variable.0472

If you look at it, you can tell--why is it an instance variable?--It has this @ sign here.0490

Next, let's look at defining the to_s method.0503

This allows us to have a string representation of that class.0509

I'm going to continue working on that hello_world method.0514

Here, we are going to...we have defined and initialized name, and we're defaulting it, now, to an empty string.0521

It says that, if I don't enter any value, it's going to enter an empty string of "", and it's going to allow me to continue that class, anyway.0536

So, I can call it without passing a parameter in.0551

Then, it goes ahead and declares and instantiates that instance variable from there.0554

Then, I'm going to declare that to_s method for that string representation.0560

It's going to create a new local variable called name inside this scope in that function.0565

That local variable only works in that method.0571

This says, "OK, I'm using this ternary operator, so I'm saying if this instance variable, name, if that is empty, I want you to pass world in there."0575

"But, if it isn't empty, go ahead and just pass name."0588

Here it says "Hello", and it interpolates the value name, so we have two values: this could be either "Hello world!", or it's going to say, "Hello", and then it's going to have whatever this @name value is.0592

This one is if it's empty, and this one is if it's not empty.0618

For example, here I just call HelloWorld.new; since it is empty, it's going to just print out "Hello world!"0633

Let's go ahead and set up some code for this, so you can see it in action.0643

I'm running my Ruby Interpreter.0652

I'm just going to create that class, so I have my HelloWorld; I'm going to initialize it with that default parameter, so it's going to do that empty string; @name=Name...0654

Then, I'm going to declare my to_s method here, so we have if @name is empty...if it is empty, it's going to pass world; else, it's going to pass name.0671

Then, this is what I'm returning; I'm returning that local variable name.0684

There you go: I have our class initialized.0693

Now, if I do HelloWorld.new, you will notice that it prints out "Hello world!"0695

But watch this: if I do HelloWorld.new, and I pass Justin in, you will notice it changes that value to "Hello Justin!"0703

I can pass that to a value, too, and it will still create that new object, hw, but for the to_s, you will notice it still prints out "Hello [world/Justin]!"0711

Plus, I can call hw.to_s, and it will print out that string again.0724

Next, we're going to look at this value called self that is used in the class.0737

Self just means that instance, that object of that class--the instance of the class.0744

When we do this, @name belongs to the object that self refers to, so I can do self.name.0751

For example, in this value, we actually updated this class now; it's going to initialize to a first name and last name.0760

I'll show you how this is done: first, let's just go over the code very quickly.0771

Now, we have first_name and last_name; they both have default values, so if I don't pass it in, it's going to create an empty string for that.0778

It has two instance variables now: @first_name and @last_name.0786

We have a new method called name; when I call this method, name, it's going to give me the full name--first name and last name--very simple.0794

Our to_s method has been updated; notice, now I call self.name.0801

What this does is--notice, when I call self.name, it's just going to call this method up here.0809

It's going to say "Hello" with the first name and last name with it.0817

Let's go ahead and show an example of how this works.0825

Let's just declare that method again.0832

This time, we updated it, though.0836

The first_name, the last_name...and I'm declaring the instance variables now.0843

Here is where I'm going to use a little interpolation; I'm going to say, "Interpolate the first value and then interpolate the last_name value."0859

Then, the last one is--I want to do that to_s method, but this time, I'm using that self keyword.0877

Here you see, that self.name is being used.0887

Let me show you it in action: so I do HelloWorld.new of John Doe; when I press Return, I have the new with the first_name, last_name, and it actually calls that to_s method by default when I declare it.0893

It says, "Hello John Doe!"; I can also do hw.name, and it's going to do the same; it's going to print out the name; and I can also just do hw.to_s, which will call name also, but uses that self method that we created, which is an instance of that object.0913

It gives you all of these properties that you can use while inside that class object, for your own functionality.0932

Next, let's look at accessor methods.0948

The accessor method returns the value of that variable.0953

For example, we're looking, first, at this HelloWorld; we have two accessor methods here.0960

All they do is to tell you what is that value in that instance variable.0974

These are also known as getter methods.0981

The first one will get me that @first_name value; the next one will get me that @last_name value.0995

I can actually show you how these accessor methods work; I have some code I want to show you here.1009

Here we have that same code piece again, but you notice I have two accessor methods here.1020

I'm going to declare that HelloWorld object, HelloWorld.new, and I'm going to call these two methods, hw.first_name, hw.last_name, and then we can see these methods in action--see how they return that value.1032

I'm going to execute that code I just showed you, that HelloWorld; the first one--John is the first name, Doe is the last name, and it's using these accessor methods to get the value back.1055

The next thing we want to look at is setter methods; setter methods, not getter--we just went over getter methods.1077

These are also known as mutator methods.1082

They set the field to a value specified by the argument, so whatever parameter you pass in that method, that is going to be the one that it's setting, and it's going to set it to the instance variable.1088

I updated that HelloWorld class again; so this time in that HelloWorld class, here are my accessor methods, or getter methods.1102

Notice that I have made them one-liners now; I'm using semicolons to shorten it from three lines to one.1116

The reason I did that was just to show you different flexibility you can do with the Ruby code here.1124

Here, we have our setter methods.1132

Here, we have our first_name, our parameter we pass in; that parameter itself is the one that we are setting that value to.1145

Setting that value, it will go to that first_name, that instance variable.1153

Then, we have this method called last_name; it also takes one parameter, and that value will be passed into the instance variable last_name.1158

These are the setter methods; they're very simple, but they do have a convention, and this is the basic convention they follow to set that value.1166

I do have this code in action so you can see it here.1179

In this code, I have my getter methods--my accessors--and then here are the setter methods, just like we said.1185

I want to show you this code in action, so we have the whole class set up here, and I'm going to initialize the HelloWorld object here.1197

First, I'm going to call those getter methods.1208

Then, I'm going to use the setter methods to change the first_name and last_name.1211

Here it says "Jane Smith," and then, when I do puts hw, it's going to call the to_s method, and the first_name and last_name should be updated--let's see what happens.1216

We already called HelloWorld 1, and I'm going to call HelloWorld 2.1235

There you go: so, we have our two methods here; it gets the first values we set with the object; then we updated those values using setters, and it says, "Hello Jane Smith!" now.1241

Now, Ruby allows us to automate the getter and setter methods; we just hand-defined them; we got the basic convention down--what these methods are and what they do--but Ruby has these built in because they're so commonly used.1265

They provide these methods to automate them.1280

These getter and setter methods are actually defined in the Module class.1285

You can invoke these in any class definition, and they are already part of these classes, too, so you already have this library already built in the class.1293

Let's look at a few of these methods.1304

The first one is attribute reader: it's attr_reader.1306

This creates a getter method for the instance variable with the same name.1313

In our previous slide, we had first_name--the method is called first_name--it's going to do the exact same thing here.1320

It's going to have that instance variable with that same name.1329

They make it really, really easy to create these methods: you just pass in the symbol, whatever name you want to use.1334

So here, I have my class HelloWorld; I just call attr_reader, and I use this symbol for first_name and the symbol for last_name, and that is it.1340

It saves my time; it doesn't mess up my code with all these getter and setter methods; it just makes it very simple and easy to put that in your class and define it.1351

Now we have our getter method; do they have a common setter method? Yes, they do!1366

We have this attribute writer here; the attribute writer creates a setter method for the instance variable with the same name.1372

Again, all I do is do the same thing; I can just use attr_writer, and then I just put first_name, and then last_name, and that is it--the same way as the reader method.1381

But, the attribute writer isn't commonly used, because usually, you want to be able to access it and read it out if you're editing it.1416

The more commonly used one is just attribute--attr.1425

This is the real one you want to get used to; it creates both the getter and the setter methods.1429

In Ruby 1.8, you would use attribute accessor, but in 1.9, you don't have to call attribute accessor: they shrunk it down, and you just need to call attr.1439

This works with 1.9, and it's a common way to do it, and it's the popular way; I would recommend you use it.1450

So, how do you automate this getter and setter method?1465

For our example, with our HelloWorld, all I would do is...I want both those methods, so I'm going to call attr and pass my first_name and my last_name.1469

Those are going to get me that symbol value, and it's going to define those two methods for each one of them.1480

What does it give me? Since we didn't make this code, it's kind of magical, because it's using that Module class...it's going to create me a getter method called first_name and last_name.1489

Think of it--if you had just created it yourself, you would have that defined here.1501

Then, the setter method is going to be first_name with that equals sign, so you can think of it like this, too...1506

Now, we have four methods that are magically in this class.1515

That attr already handled all of the magic for us; it already created it and defined it for us.1523

There are some things you need to know about using Ruby's accessor methods.1533

First, one good thing is that they run as fast as if you had hand-coded them yourself, so there is no time penalty for that.1541

The important thing is that these do map the same instance variable name--whatever symbol you give it, it's going to be the same name for that method and that variable.1555

So, if you needed something more complex, like a more complex accessor with a differently-named variable, you would need to define them yourself.1564

If I call method first_name, but I want to tell it to go to a different instance variable, then this wouldn't work in that case, because it has to all be preserved in that same name.1577

I would definitely say to check out Ruby's accessor methods and play around with the class.1593

Other than that, that is the end of the first part of the classes.1600

See you next time at Educator.com, and we will go on to the next class lesson after this.1606