Learn Ruby the Hard Way – Exercise 19 Functions and Variables

Here is the work for Exercise 19.

Exercise 19 code
Exercise 19 code
Exercise 19 output
Exercise 19 output

Study Drills
1. Go back through the script and type a comment above each line explaining in English what it does.

Commented Exercise 19 code
Commented Exercise 19 code

2. Start at the bottom and read each line backward, saying all the important characters.
Read.

3. Write at least one more function of your own design, and run it 10 different ways.
I wrote a function that prints two lines, each line asks whether the number is even and answers true or false. I call the function 10 different ways: using math calculations (addition, modulus, exponents, division) and also call the function with numbers from user input. 

My is_even function
My is_even function
Now we see whether the numbers we entered are even!
Now we see whether the numbers we entered are even!

Summary
This exercise is building upon the introduction to functions in the last exercise. Functions can take any number of arguments (but the practical limit is about 5). Variables inside a function are not connected to variables outside of the function. When outside variables are passed into a function as arguments, temporary versions of these variables are made for use within the function. When the function ends, these temporary variables are gone.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s