Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Let's practice some basic Ruby to make sure that everything you've learned so far sticks. We'll review numeric types such as Fixnum and Float, as well as math operations.
These videos cover the concepts you'll need to complete the exercise:
[MUSIC]
0:00
Let's practice some basic Ruby to make
sure that everything you've learned so
0:04
far sticks.
0:08
We'll review numeric types such as fix,
num and float, as well as math operations.
0:09
We're gonna ask you to build a simple Ruby
program that calculates the average of
0:14
some numbers.
0:18
I've attached a work space to this
video which includes an average .rb
0:19
starter file,
with instructions as Ruby comments.
0:23
You should open the work space now.
0:26
If you have Ruby installed on your
computer you can choose file,
0:29
download work space.
0:32
And that will download
all the files to your
0:33
computer where you can edit and run them.
0:38
Or you can just set it and
run everything in the work space.
0:40
Write your code in the average.rb file and
save your work.
0:44
Then switch to the terminal and
type ruby average.rb to run your program.
0:47
Up here at the top of the file
we've already defined four Ruby
0:53
variables for you.
0:56
Your job is to take the value
of all those variables and
0:57
calculate the average,
that is the mean of them.
1:00
You can do this by adding all
their values together and
1:03
then dividing by the number of values,
that's four values in this case.
1:06
Now there's a little catch to this,
for the numbers 12, 7, 5 and 10,
1:11
you should get an average of 8.5, not 8.
1:14
If you find that you got
the number of 8 even,
1:18
it's probably because you divided
by a fixed sum, an integer.
1:21
So make sure that you're
dividing by a float instead.
1:24
See the teacher's notes for
1:27
videos that can help you fix
this problem if it arises.
1:29
There's an extra credit problem down
here at the bottom you can try.
1:33
You can prompt the user for some values
to average by populating the E, B, C and
1:35
D variables by calling the get s method.
1:40
Note however, that the get s method
returns the string not a number.
1:44
So you'll need to call
the to_f method on the value
1:47
returned by gets to convert it to a float.
1:50
That is when we type gets.to_f and
then store that value in a variable.
1:53
Then you can calculate an average of all
the variables as you did previously.
1:59
I've linked to some videos in
the teacher's notes which you can refer to
2:03
if you get stuck.
2:07
After you've written your program
you can proceed to the next video
2:09
where you can compare
my solution to yours.
2:11
Ready?
2:14
Get started on your program.
2:15
I'll show you my version and
the next video.
2:16
You need to sign up for Treehouse in order to download course files.
Sign up