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