Ruby: Methods

Why Write Methods?

As programs get more complex it makes sense to define methods.  

They can be reused without repeating code blocks.

We want to keep our code as DRY (Don't Repeat Yourself) as possible. 

def my_first_method

end
def dont_repeat_yourself
    
    #my program will perform this action again and again!

end

Method Madness

Methods can do as much or as little as you need them to do.

def hello
    puts "Hello universe!"
end

def really_hard_math
    answer = (-5 + Math.sqrt(5**2 - 4 * (8*15)))/(2 * 8)
    puts answer 
end

When called upon

A method will not be performed until it is "called".

# define the method:
def add_it_up
    sum = 3 + 5
    puts sum
end

# now call the method!
add_it_up
$ ruby adding.rb
8
$

Return To Sender

A method can do more than just print to screen its results.

def two_plus_two
    sum = 2 + 2
    return sum
end

The command return gives the method a value.

We have a couple options when calling the method:

def two_plus_two
    sum = 2 + 2
    return sum
end

puts two_plus_two 
# prints the value returned by the method returns

answer = two_plus_two
# assigns the value returned by the method to a variable

Ruby Magic: No Return Needed

You don't even need to put return at the end of a method:

Ruby will return the last value assigned.

def two_plus_two
    sum = 2 + 2
end

puts two_plus_two
$ ruby add_it.rb
4
$

Give Me Something to Work With

You can give a method arguments or parameters (passed values) to play with!

def add_it_up(num1, num2)
    sum = num1 + num2
end

puts add_it_up(4, 5)
#what would be printed to screen?

You can pass variables from outside the method via parameters.

def add_it_up(num1, num2)
    sum = num1 + num2
end

time = 4
space = 5

puts add_it_up(time, space)

Let's Get Methodical

Let's try some exercises to practice writing methods...

Write a program that takes a String argument and outputs the String in reverse.

Create a method for converting weight from pounds to kilos.

Write a program that prompts you for a String and then outputs the length of the String.

The ULTIMATE challenge!

In Ruby 6 / 4 == 1.

 

But what if we want the remainder also?

Write a program that asks for two (2) Integers, divides the first by the second and returns the result including the remainder.

 

If either of the numbers is not an Integer, then don't accept the number and ask again.

 

Do not accept zero (0) as a number.

Ruby Methods

By argroch

Ruby Methods

  • 1,006