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
Now that a gem is installed, we need to know how to use it.
Code Samples
Once a gem is installed, it is used by calling the require
statement followed by the name of the gem. If we were using the money
gem, it would look like this:
require 'money'
Now that we know what
gem we want to use and
0:00
have it installed, we have to be
able to use it in our program.
0:03
Let's see how that works
now using work spaces.
0:07
So now that we have the money gem
installed, let's go ahead and
0:11
see how to use it in one of our programs.
0:14
First, I'm actually going to scroll
down the right side of the screen
0:17
on the ruby gem documentation page, and
0:20
I'm going to click the documentation link,
and then we'll see what it gives us.
0:23
Right now, I'm going to click
on the API documentation, and
0:32
then, let's see how to use
it in one of our programs.
0:37
Well, we've done the gem install, so
let's go ahead and see how to use it.
0:40
In this example, there's $10 US.
0:46
Now first, we'll need to require the gem,
0:49
s o let's go back to our work space and
create a new file.
0:51
We're going to call this money example.rb.
0:58
Now once a gem is installed, the first
thing that we need to do is require it.
1:05
So, we’ll require money.
1:10
If only it were that easy in life.
1:14
Now that it’s required we can use it,
so I’m going to go back and
1:17
consult the documentation.
1:20
It looks like we can initialize a new
money instance by calling the class name
1:23
money, and the word new, and then give
it the number of cents in a currency.
1:27
Let's go ahead and try that.
1:33
And, for right now,
let's just print that to the screen.
1:42
Now, I'm gonna click down into
the console, and run this program,
1:49
and it gives us a money instance.
1:55
So, at this point, we've installed a gem,
and used it in a very simple program.
2:00
Let's go ahead and
create another one, more_money.
2:07
And let's print this
to the screen as well.
2:22
Run this one more time, and
2:26
we can see that we have successfully
added two units of money together.
2:29
And that's really all that's required to
use a gem once we've got it installed.
2:35
Just use the require statement.
2:40
Ruby will then find the gem and
import it for you in to your program.
2:43
Generally, the require statement is
going to be the same name as the gem.
2:49
In this example it was called money.
2:54
If we had installed another gem,
such as multi jason,
2:57
we would require multi jason instead.
3:00
You need to sign up for Treehouse in order to download course files.
Sign up