How to include a Ruby Gem in a program or app.

When you first start programming in Ruby it can be confusing what a gem is and how to use them properly in your program. A gem is a packet of ruby code that serves a variety of different functions.

For example, the Faker gem can be used to quickly and easily generate random data. This data can be used anywhere in your Ruby program, you can have one line of code that will quickly generate random names, or numbers or quotes, or pretty much anything Faker can generate.

There are a multitude of different gems, all serving a ton of different uses. It can be confusing where to start. Gems are available for searching on the website,

From there you can click on Install RubyGems and download the RubyGems folder.

Download the ZIP file and unzip it into a folder, but make sure you remember the location of the folder that you are unzipping it into.

Once the file is unzipped, go into your terminal and navigate to the unzipped file using cd ../locationoffile where locationoffile is the folder that you unzipped. Once in the correct location run the command ruby setup.rb and RubyGems will be installed.

This will allow you to install gems from the command line, as long as you know the name of the gem you will be able to install it into your ruby system.

Including A Gem Within a Ruby Program.

To install and make use of a gem, within a ruby program, the command is simple. gem install ‘NameOfGem’ I will use Faker as an example for the rest of this post. So to install the Faker gem I would run the command, gem install faker. RubyGems will then take over and install the Faker gem for your use within your Ruby environment.

But simply installing a gem is not enough to begin using it. The Faker documentation can be found on the GitHub page for the gem. If you scroll down the ReadMe page until you get to the name attribute:

you will see that you have a choice of different commands to use to generate some random names.

If you go into a .rb and just put you will not generate any random data. There is one more step you need to do to use a gem. That is the require line. require ‘faker’ needs to be a line in your code for the gem to fully be utilized. If you are running a rails app, it can be put anywhere in the Gemfile file, but if you are running a regular .rb program it needs to be included in the file that you running. Including that one line will then allow you to use all the Faker commands found in the documentation.