DEV Community

aryaziai
aryaziai

Posted on • Updated on

Having Fun w/ Ruby Gems

I recently began learning Ruby as my first programming language. Before I became interested in programming, I was an avid Wordpress user. When I first started using Wordpress, I had no idea what I was doing (similar to my experience with Ruby thus far).

Alt Text

I think about this meme often

What helped me become more comfortable with Wordpress was a thing called "plugins." A wordpress plugin is code that contains a group of functions that can help extend functionality on your site once they are installed. This is very similar to Ruby gems, which are packaged code that someone else has written to help save you time from coding the methods yourself.

The first time that a ruby gem caught my attention was when an instructor used the Faker Gem. The Faker gem helps generates random data, such as names and foods, to help populate the ruby program. Below is a quick example of Faker generating a random name:

Alt Text

In order to output "Clemmie Nienow PhD" in my console, I simply followed five quick steps.

1) Create a gemfile file in my working directory, and add the following code to it:
source "https://rubygems.org"
gem 'faker'

2) Next run bundle in the console in order to add to your project dependencies. Other people will now be able to clone your code and run bundle to include the project dependencies. If you don't have bundler installed on your system, follow these steps: https://help.dreamhost.com/hc/en-us/articles/115001070131-Using-Bundler-to-install-Ruby-gems

3) Add require 'faker' to the top of the file that you want (i.e. run.rb file).

4) Read the faker documentation to see how we can utilize Faker.

Alt Text

5) Run the ruby file (i.e. ruby bin/run.rb) and your done!

So what's next?

Now that we understand the basic idea of ruby gems, we can look through the gem libraries and install something new. First, we'll visit https://rubygems.org/. Rubygems.org is the main repository of ruby gems and includes over 10,000 gems.

Alt Text

Now let's search for a gem. Several of my friends are having birthdays coming up and I don't have any time to write them a card. Let's see if we can find a gem that will output a message for me. Let's search Happy birthday

Alt TextThis seems like a cool gem! We already know that we'll need to add it our gemfile and 'require' it at the top of our code, but how do we utilize the gem? Let's check out the documentation link.

Alt Text

Let's create a new instance for bday and assign to the bday variable. Next line we'll just print the bday variable.

Alt Text

Done!

Discussion (0)