Introduction to methods

What is a method?

Let's say, for now, that a method is instructions on how to do something. Think of it like, answering the following questions: - What steps do I need to bake a cake? - what steps do I need to start an aeroplane and take off?

The answer to the above questions will be the steps you will have to follow in a particular order to make it happen. You have to follow these steps in the order they are given to you otherwise your aeroplane will never take off.

These steps will always achieve what you want as long as you follow them in the order they are given, that is, the steps described above are assumed to be repeatable. Okay let's have fun with the plane then:

Steps for flying a plane

NB: The following has been summarised from a wikihow article, if interested, follow the link later to read more about it 1. Perform an inspection before getting in - check on fuel tank , emergency supplies etc 1. Locate the flight control on the cockpit 1. Check on the fuel mixture controls - more like the fuel guage 1. Locate the landing gear 1. Get permission to take off 1. Adjust the flaps to the proper angle for takeoff 1. Perform an aircraft run-up procedure 1. Notify the tower that you're ready for takeoff. 1. Start the take-off run

You dont have to understand whats gooing on in the steps above but in back of your head I assume you are imagining if you skip a single step you might crush back to the ground or collide with another plane on the runway, right?

crush landing plane

If someone had to give these instructions verbally every time before you take off that would sound every boring. If it was you giving the instructions what would you have done about it?

I would have written them down somewhere so anyone who wants to take off a plane would come and just read. Did you think about that? If you did, awesome. Next thing I would do is to give the instructions a title, more like what you see below

Instructions on taking off

The instructions above have a title taking off a plane, this describes the steps involved

Enough aeronautics, back to programming now.....

In ruby a method describes steps taken to achieve a task. Every time you use the method, all the steps are followed to the last one inside the method

Using the instructions written above for taking off a plane, we can say that our method is the title of the task which is taking off a plane. Lets then define the method in ruby.

def taking off a plane
  # Perform an inspection before getting in - check on fuel tank , emergency supplies etc
  # Locate the flight control on the cockpit
  # Check on the fuel mixture controls - more like the fuel guage
  # Locate the landing gear
  # Get permission to take off
  # Adjust the flaps to the proper angle for takeoff
  # Perform an aircraft run-up procedure
  # Notify the tower that you're ready for takeoff.
  # Start the take-off run

Something is not right with our method definition above, do you remember what we covered during the prep course on ruby methods? Use that knowledge to spot the problem. This time I am not going to tell you what the answer is (smile)

Hint: Check on the naming conventions of methods

Structure of method calls

As we said before, all methods are called on something just like instructions are given to someone, its never just thrown out. Lets look at the structure of ruby instructions (methods)

We have two parts

  • the caller

  • the instruction

If someone writes your name with mixed cases e.g "YouRNamE" but you want it to be written well. Lets jump into irb and write the following

irb> "YouRNamE".capitalize

"YouRNamE" in this case the caller since it calls the method capitalize

The instruction is capitalize which then gives use a capitalized version of our name

The . (dot) is usually a seperator of the caller and the instruction. In ruby it is possible to call one method after the other e.g

irb> "YouRNamE".capitalize.reverse

The first instruction is executed first then the next, so in this case we capitalize the name after which we take the capitalized name and reverse it

Some fun facts about methods

  • They have rules on how they should be written - Do you remember the rules?
  • Using methods in ruby is commonly known as calling a method
  • Methods are called on an object all the time, for instance our method above is called on the plane
  • The last step in a method is what the method always thinks is the truth and always gives you that step
  • whenever a caller calls a method, the method must always bring something back to it (this is usually known as the return value)

Inbuilt methods

Some methods are so common that ruby comes with them so we do not have to keep defining them all the time. Where did the capitalize method come from? We never defined it, it was defined by ruby.

Once rubyists (those who create and use ruby) create the methods they need to let us know how to use them. This is done via something called the documentation

Looking up inbuilt methods

Follow this link to the ruby documentation on working with strings

TODO: write on how to use the official ruby docs. For now explain to the student how it is used

Using the documentation

Look up on the ruby documentation, methods that can help you achieve the following and use them

  1. find the positive value of a negative number
  2. count the number of charaters in your name
  3. find out if a number is an even number
  4. make all uppercases lowecase and all lowecases uppercases

User defined methods

Ruby documentation has a vast and wide range of methods, the widest I ever seen(sense my bias).But like everything it has limitation not all methods in ruby will suit our needs that's when we right our own methods

Method generally consists of three parts: - name - parameter - body

General methods syntax is like so:

irb session

Name is a variable that represent that method, just like in variable declaration you say you declaring, with that give name in our case sum but use defining you will sounds smart and that is what is.

Parameter is a variable used to represent actual value during method call

Body what contain the return value of a method, this where the actually instruction how data is transformed is placed.

Some practice on methods

If you have not at this point heard of or used irb, let me introduce it to you. It is a playground provided to you where you can can write ruby and see the results of what you have written.

To open it, open your terminal and type in irb then type the following looking at the results

  1. 1+1

  2. 3*5

  3. define a method, my_name that returns your name

  4. call the method you defined above

  5. Define more methods on irb and call them, define methods that also call methods

irb session

The return value

The return value is the expect output of a method, and it ussually the last statement inside the body of a ruby method, unlike other programming language where you must explicity use the keyword return.

For instance this is a python method

def sum(a, b):
    return a +b

With telling in when to return python method will never return, in there world they call method, function(it makes me laugh all time since they claim to be OOP you will get the joke when talk about object soon).

This is not the case for the last statement inside the method body will all be returned unless stated otherwise.Let's this otherwise moments.

  > def buggy_sum(a,b)
  >  return a * b
  >  a + b
  > end
  => :buggy_sum  

Look at code and what do thing return value will be if I call with arguements 6 and 7 i.e buggy_sum(6, 7).You expect that 13 right?, Let's call and see

  > buggy_sum(6, 7)
  => 42

That is somehow akward with 42 instead of 13.This not an error you explicitly told ruby to return the product of arguements passed and it loyally did execution stop with when it came across return.This kind of execution is common where control flow(if, unless and the likes) is applied.

I want you to remember this it is ruby convention to never explicitly use the keyword return inside a method body and that the last statement inside method is what will be returned. Therefore you will hardly see this keyword used.