Expand All

Functions

A function is a step in a process. Think back to the last recipe you cooked. There were steps like 'mix', 'measure', and 'bake'.

Goals

  • Create a function

  • Call a function

Step 1

In your text editor, create a new file called area.rb

Type this in the file area.rb:
def calculate_circle_area(radius)
  Math::PI * (radius ** 2)
end

print "What is the radius of your circle? > "
radius = gets.to_i

puts "Your circle has an area of #{calculate_circle_area(radius)}"

Save your work.

Step 2

Run the file.

Type this in the terminal:
ruby area.rb

When prompted, type in a radius for your circle and hit return.

Step 3

We can write functions in IRB too.

Type this in irb:
  def backwards( phrase )
    phrase.reverse
  end

A function begins with def. It's followed by the name of the function, and then a list of what you plan to send in.

Inside the function is the code that does the work. The function ends with a statement that evaluates to a function. What does it mean to evaluate a statement? When we type `puts "Two plus two is #{2 + 2}", Ruby evaluates the statement inside the curly brackets. 2 + 2 evaluates to 4, and 3 < 9 evaluates to true. "Hello".reverse evaluates to "olleH". The function hands the value back by saying it.

After you typed 'end' and hit return, irb typed nil. This is fine. Ruby always reports what it got when it ran your command, and functions result in nil.

... and then call our function:

To call a function, first say the name of the function, then send in the values the function needs to do its job.

Type this in irb:
backwards 'Hello' 

Step 4

We can store the result in a variable.

Type this in irb:
mirror = backwards 'Hello'

Explicación

As your programs get more and more complicated, you'll want to group code into functions that can be called over and over again.

Pedantic Programmers might want to tell you that Ruby doesn't technically have functions, and everything in Ruby is really a method. It is appropriate to slap these people.

Next Step: