What is a function?¶
A function is a method that is not associated with any particular object. You have already seen one function: “puts”. Notice the syntax:
puts "Hello"
Hello World with a function¶
Here is a simple function:
def say_hi
puts "Hello, How are you?"
end
Now we have defined the function say_hi. When you call the function “say_hi”, the block of code you specified gets called. For example:
def say_hi
puts "Hello, How are you?"
end
say_hi
say_hi
Will produce:
"Hello, How are you?"
"Hello, How are you?"
As you can see, functions are the first step in code reuse.
Function parameters¶
Functions and methods can be passed parameters. Here is an improved say_hi function.
# 'name' contains the user input
def say_hi(name)
puts "Hello " + name + ", How are you?"
end
say_hi("Daniel")
say_hi "Sandy"
This produces:
Hello Daniel, How are you?
Hello Sandy, How are you?
When passing arguments to a function, we can leave off the parenthesis. However, the parenthesis are required in cases where leaving them off makes the code ambiguous.
Printing an address¶
Now let’s write a more useful function. Recall the address structures:
# Melissa's address
melissa_addr = {
"street" => "23 St George St.",
"city" => "Silver Spring",
"state" => "MD",
"zip" => "20465"
}
# Sandy's address
sandy_addr = {
"street" => "324 Campus Dr.",
"city" => "College Park",
"state" => "MD",
"zip" => "23659"
}
Let’s make a function to print them:
def print_addr(address)
state = address["state"]
zip = address["zip"]
puts " " + address["street"]
puts " " + address["city"]
puts " " + state ", " + zip
end
Now we can easily print addresses with:
puts "Melissa:"
print_addr(melissa_addr)
puts "Sandy:"
print_addr(sandy_addr)
And this prints:
Melissa:
23 St George St.
Silver Spring
MD, 20465
Sandy:
324 Campus Dr.
College Park
MD, 23659