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

Bookmark and Share

Start Learning Now

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

Sign up for

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!

Methods: Part 1

  • A method provides a way to gather statements and expressions into one area
  • It can be used repeatedly to execute a specific task
  • It can be defined to do all sorts of tasks
  • The return keyword forces a return to the end of the method
  • Any value following the return value will also be returned
  • The method undef allows you to undefine instance methods
  • Method names should begin with a lowercase letter
  • When longer than a word, it should be separated with underscores
  • A method name with a question mark answers the question posed by the method
  • Usually it returns true or false
  • A method name with an exclamation point is usually a mutator method
  • The exclamation point means to use it with caution
  • Method aliases allow you to define a new name to an existing method
  • Operator methods can be defined in your own class
  • Methods can be associated with code blocks
  • The method block_given? will return true if a block is passed

Methods: Part 1

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
  • What is a Method? 0:12
  • Basic Method 0:58
  • Return Value 4:37
    • return
  • Factorial Example 6:18
    • Example
  • Return Two Values 10:06
    • Set the return keyword
    • Collected and returned as an array
  • Undefining Methods 11:22
    • undef method_to_undefine
    • Example
  • Method Names 13:02
    • Begin with lowercase letter
    • Separate longer words with underscores
    • Can end with equal sign, question mark, or exclamation point
    • Equal sign
  • Method Names with Question Mark 14:44
    • empty?
  • Method Names with Exclamation Point 16:01
    • mutators
    • ! means use with caution
  • Method Aliases 18:05
    • alias new_method existing_method
  • Operator Methods 20:00
    • Operators
    • Array Operators
    • Unary Operators
    • Binary Operators
    • Example
  • Methods and Parentheses 25:00
    • Optional in most cases
    • Required in other cases
  • Methods and Blocks 27:54
    • Associated with blocks
    • block_given?
    • yield
    • Example

Transcription: Methods: Part 1

Hi! Welcome back to

Today's lesson is on Methods, Part 1.0002

What is a method? It provides a way to gather statements and expressions into one area.0009

It can be used repeatedly to execute a specific task.0020

Methods can be defined to do all sorts of tasks.0026

You will definitely be using methods quite often; you have seen a bunch of methods already in a lot of previous lessons we've done.0035

The goal of this lesson is to get you very, very understanding of all the basics of a method so, going forward, it clears a lot of questions you will have.0043

Let's first look at a very basic method that you will commonly see.0055

Parts of a basic method: you will see parameters--notice, for this one, it only has one parameter; in this case, there is just one parameter.0062

You will also notice, for this method, it takes one parameter, but it also has a default value; that default value for that parameter is 0.0079

Quite often, in other languages, they have to overload the function to do this type of behavior, but only Ruby has this default parameter set up.0096

There is a return value, and depending on what is in the parameter, it will return different things.0113

That is another thing you have--a return value.0129

Notice that this method doesn't have the word 'return' that you will often see; since this is the last statement, these will be returned, though.0136

If I pass hello_world without any parameters, it will default n to 0, and that means it will display "Hi!".0153

If n is greater than 1, it will print out "Hello worlds!"; if it's equal to 1, it will print out "Hello world!"; and else, it will do "Hi!".0170

You will see here, as I called the method, hello_world, there are 0 parameters, and it just prints out "Hi!".0181

You will notice that this is the return value, and that is a string.0195

Again, I could also pass hello_world, and if I pass in 2, it would give me "Hello worlds!".0204

If I could also--notice, I didn't put parentheses there--but if I also did hello_world, and I passed in 1, it would return to me "Hello world!".0227

You will also notice that the actual name uses an underscore; quite often in Ruby, you will see underscores for all the methods: you will not see CamelCase.0252

This is just normal convention in Ruby.0267

OK, let's go to the next one.0273

We just saw three different return values; let's look further into this return value.0276

You can actually explicitly write return; when you do that, this return keyword forces a return to the end of the method.0285

If you put anything below it, it's not going to get to it--it's just going to return after it sees this keyword--so that is a very important keyword.0297

Also, any value that is following that return value will also be returned.0307

If I pass in a String after that return, an Integer, whatever object I pass--it's going to be returned with it.0313

Return and whatever object this is...and this object can be anything.0323

It can be a String; it can be an Integer, a Float, an object you created...0330

Most often, you won't see any return value in the code.0346

Usually, it's omitted when it's not required, as you saw in that basic method--it didn't have any return values.0354

It's already the last statement at the end; it's already going to be returned, anyway; so there is no reason to explicitly tell it.0361

Let's go through some examples where you will see it.0370

Right here, I have a factorial example; this will give you the factorial, depending on the parameter put in.0375

See here, our method factorial takes one argument; it returns 1 if you pass y=0.0384

Notice that it just returns: that means that it ignores this next line; so if y=0, it's going to ignore this line over here, but if it is 1 or greater, then it's going to call this method here.0395

This method actually calls itself; so, if I did 3, it would do 3 times factorial...and 3-1, we have a 2, and after that, it calls factorial of 2...that will get you 2...times factorial 1.0413

Here is where we get that 1; this is going to break down, 1 times factorial 0, and notice, when it hits 0, it sees that over here: it says, "OK, that y value is equal to 0--I'm just going to return 1."--so that is 1.0453

Now that we have broken down what all the different factorials are, here is what it gets when I pass factorial 3--remember, this is for factorial 3: when I do that, it's going to do 3 times 2 times 1 times 1, and we get, at the end, 6.0476

Let's go through some code of this example; I want to show you what you can do without the return value, too.0511

We have our terminal here; let's first specify the method.0525

Again, I'm putting one parameter there: I'm going to return 1 if that y=0, but instead of having that second return value--it's not needed, since it's the last line of this method--I'm not going to do it.0531

I'm just going to put return, y times factorial, y minus 1, and then I'm just going to end it.0548

Let's see it in action: if I do factorial 0, I get 1; factorial 1, I get 1 also; 2--that is 2 times 1--I get 2; 3--which is 3 times 2 times 1--6; 4--we get 24; and 5--120.0562

Notice, we didn't even have to use that return value.0593

That is our factorial example.0601

Now, Ruby allows you to return two values; you must explicitly set that return value in this case.0604

If you are returning two values, you have to explicitly set the return.0617

That return value is collected, and it's returned as an Array.0624

We have an example here: I have this method called square_it; it takes two arguments, and those two arguments you pass in--it's going to take them to the power of 2 and just return it.0631

Notice, on my return value, I actually didn't put any parentheses, and it allows that.0646

I have the comma, and my 'to the power of 2' if I call square_it and pass in my two values, my return is an Array of 4 and 25.0655

It's going to take 2 squared and 5 squared and put that into an Array.0671

The next thing I want to talk about is undefining methods.0682

You probably won't use this too often, but it's still useful to know, because there will come a time when you will need it, and it's good to know it.0688

To do this, the key action value is undef: you call that and the method you want to undefine, and it will make that disappear.0699

This takes one parameter, an identifier that specifies the method name.0716

It works in classes to undefine instance methods.0722

So, if you are in a class, and you are going to undefine these instance methods, you can also undefine the inherited methods.0727

For those previous examples, if I do undef(square_it), undef(factorial), it does not exist anymore; if I call those functions again, it's just going to give me an error.0735

I can actually go to the terminal...and we still have the factorial in memory, so if I do factorial(5), I get 120.0748

Now, if I call undef(factorial), and then I call it again, now it says "NameError: undefined local variable or method 'factorial' for main:Object" since I have created this method in the global scope.0757

The next thing we want to look at is method names.0781

Method names should begin with a lowercase letter, unlike classes that still use that CamelCasing.0787

When longer than a word, separate the words with an underscore: that is key.0802

Maybe in another language, you see this HelloWorld; it follows this CamelCase convention; but in Ruby, when you are creating methods, this is the way to go.0811

It's going to say hello_world; it spaces the two words out, and it uses underscores to do that.0830

The next thing I want to talk about will see methods with an equals sign after them, a question mark, and an exclamation point.0843

We have our equals sign here, and our exclamation point, and our question mark.0852

First, let's just look at the equals sign.0860

Equals sign means the method is a setter and that it can be invoked using an assignment syntax.0863

Follow these rules: if you are creating a method with an equals sign, that means that method is a setter.0870

Now, let's look at methods with question marks.0883

When the method name has a question mark at the end, this means it answers the question posed by the method.0890

Usually, it returns a Boolean value, true or false; sometimes, instead of false, you will get nil.0900

For example, let's just look at the empty? method--it's 'empty?'--it has a question mark at the end.0911

You know that it is contained in a wide variety of objects: so, in Array, if an Array has no elements, it will return true.0920

It's also defined in the String object; so, if a String has 0 characters, it will return true.0934

And, of course, you can create your own empty? method for your own objects, and you can define them yourself with what you need it to do--what does empty mean in your object?0944

The next thing is to look at method names with exclamation points--an exclamation point at the end.0960

Usually, these methods are mutators; that is the common thing.0970

What is a mutator? A mutator alters the state of an object.0979

This exclamation point will actually change the existing object, in most cases.0987

You will also see other methods that don't use exclamation points, and they still change the object--like delete.0995

So, why the exclamation point--why do you put it in? The exclamation point means to use it with caution.1002

This is the significance of that exclamation point.1011

It's going to change the object; it might do something else, but an exclamation point means, "Be careful when you use this!"1019

For example, I have this Numbers--it has three elements in this array.1028

I'm calling this sort!--notice I have that exclamation point.1035

That will actually change this existing object here, and it's going to sort that.1040

This Numbers object now has been changed to be an Array of three elements, but sorted to be [1, 2, 3].1049

Remember, if I didn't have that exclamation point--I just called sort--it would create a new object; it wouldn't modify the existing object.1064

That one is just Numbers.sort.1071

Just remember, with the exclamation point, you have to be more cautious.1076

OK, let's look at method aliases next.1083

This defines a new name for an existing method.1089

With a method alias, you can give a method another name, and you can use both of them.1095

It's not uncommon to have more than one name, so it's not a problem, and Ruby makes it really easy to do this.1109

The key here is this keyword called alias.1117

What you do is...the first parameter you put in is the new method you want to give it.1124

What is the new name you want to give this method?1134

Then, you need to pass in the existing method's name.1139

It takes those three elements.1145

So, you have to pass alias, the new method name you want to give it, and the existing method name that it is right now.1149

Very simple example: we have this method called hi_world--it returns "Hi"--and I want to give it another method name, an alias.1159

I'm going to call alias and pass in the new method hello_world, and the existing method hi_world.1171

Now, when I call hello_world, it will return me that value "Hi"--just as if I called hi_world, it will return that value "Hi" to me.1180

Next, let's look at operator methods.1196

Operators can be defined in your own class.1200

The Array operators, the square bracket and the square bracket equal, can take any number of arguments.1206

These operators are quite different from other ones you will see.1221

If you look at unary operators, they take no arguments at all.1228

Binary operators are passed on argument, so they operate on self and the argument.1235

Examples of a binary operator are plus, minus, multiplication...1245

Example here: if I have the plus operator, I call define, put + and the other argument; and then I can go ahead and put my code here and end it.1252

That is very, very basic; let's get deeper with how this works, with this binary operator.1273

I'm going to create a class and have a couple of these binary methods in there.1283

Here is my class: let's call it SuperClass; I have a constructor that takes one String value...and now, I'm going to actually create my binary operator.1295

I do my addition; I say it's going to take a parameter called other_value; and this will actually update this value that is in this object.1311

It's going to append the other value to that string.1324

Then, I'm going to make another one with a minus sign.1333

This will do the exact opposite: whatever that other_value is, it's going to remove it from the string.1336

To do that in my code, I'm going to use a method called gsub; it's going to update the value in place.1342

I'm going to pass Regexp here, so it's going to first look for that other_value, look for any spaces around that value, remove any spaces around it...and then, it's going to return it as that value.1356

OK, it looks like I actually missed the multiplication sign...1381

Let's try that again...let's see if I can, I'm going to define that again.1393

Again, I'm just creating my constructor, and I'm going to make my other_value.1411

Notice, I can also use interpolation here: since I'm not worrying about that right now--I'm just showing the method--I'm not going to do anything of that sort.1425

Here is my regular expression; it's going to remove other_value.1439

Make sure I got that right...1452

OK, so, I have my object, my SuperClass, done.1458

The first thing we're going to do is initialize it.1463

I've created my object; my constructor created a value called SuperString in this object.1471

Now, I'm going to show you, live, that binary operator in action.1478

If I take my object, and I do at...and I'm going to say it's SuperString, but it has 'goop' in it SC plus that string's going to use this operator here...and the return value is 'SuperString with goop', which is my new value in that object.1483

The same thing--I can subtract it out, so if I do SC minus 'goop', notice it removes that whole word.1510

So, now it's 'SuperString with'; that doesn't sound that good, so I want to remove that 'with', also.1519

Now, it says 'SuperString'; let's say 'with SuperOperators', since we have the new binary operators.1526

There you go: 'SuperString with SuperOperators'.1534

That is a case with all the different binary operators in it, and it works!1539

The next thing we're going to look at is methods and parentheses.1559

In most cases, parentheses are optional; it's more on your programming...what you like better: do you like parentheses or not?1566

Parentheses are optional in most cases.1580

If you have this puts method, you will notice that a lot of times I don't use parentheses with it, but with parentheses--they both work the same way.1588

They will both print out 'hello world' at the end.1597

You can also just print a string called 'hello world'.1603

I have this value 'Hi', and when I call the link method, which is part of this string, it will return me the number of characters.1611

But notice, I can return it with parentheses or none; both of them will still work.1620

There are cases where it is required, though, so let's go over those.1632

The main one is method invocations with more than one argument; this is a case where it is required.1637

For example, I have a method that takes two arguments; if I don't put these parentheses, it's going to show me a warning that says, "That's not proper; I don't know if it's being used for a method or something else."1647

So, you always want to add the parentheses in this case.1664

The last thing I want to go over is methods and blocks.1674

When you define a method, you can also pass a block in there.1681

You can use yield, and it will pass that value into the block you gave it.1687

Methods can be associated with blocks.1695

There is a value called block_given?; this returns true if a block is passed.1701

Using that, you can do different processes in this method.1711

Yield will call the block within the method.1715

So this block--now, using this yield command, you can actually tell it when to call it.1719

I have this method called processor: it takes one value, a number value.1725

Now, if a block is given, I'm going to say, "Process it using that block; I don't know what that is, but process it with it--you must know what you want to process it for if you have the block there; else, I'm going to process it myself."1735

I'm just going to multiply whatever that parameter is by itself; so it's num squared.1750

Let's go for a little example of how the block is used.1757

I'm going to create that processor that takes that parameter num; "If block is given, go ahead and process it using it; else, go ahead and just square it up."1764

If I just do processor(2), it returns me 4; I'm processing it now.1785

Now, let's go ahead and do it this time with 2 again, but this time let's pass in a value--let's say I want to do that argument and add 5 to it.1796

This returns 7 now; it uses the block I did, and we passed in 2, so it's 2+5.1814

I can do this with other values, too--I pass 10 in there, and then just do x times 2, and it says 20 instead of 10 times 10, which is 100.1822

I can change that to minus, and notice I return 8.1838

I can change the parameter, too, and it will return a different value.1846

That is the methods and blocks; that is actually the last thing I wanted to go over for this methods lesson, in Part 1.1857

Join me in the second lesson, where we go over deeper parts in the methods, and give you a better feel of all the different pieces to it.1867

Until then, see you next time at!1880