Create your first gem in ruby.

Ever wondered how can you create your own library in ruby. Here’s a tutorial to create a simple library in ruby which ruby coders call gem.

RubyGems are package manger which are used to install various gems(libraries) to your system. Just like we use pip in python.

Let’s Begin

File Structure:

GemSpec file
This file contains the specification of your gem that describes your gem. do |s| = "my_gem"
s.version = "0.0.1" = "2018-07-02"
s.summary = "My new gem"
s.authors = ["Shivam"]
s.files = ['lib/my_gem.rb']
s.require_paths = ["lib"]

Here describes the name of your gem. Similarly, version, date and summary are self-explanatory. Now, s.authors describes the author of gem, s.files lists all the files that are included in gem and s.require_paths specifies the directory that contains the Ruby files that should be loaded with the gem.

Steps to create gem file:
Open your terminal and enter these commands:

mkdir my_gem
cd my_gem
mkdir lib

Create the Gemspec file:

vi my_gem.gemspec

and copy the above code.

Add Files to your libray:

cd lib
vi my_gem.rb

Copy the code below in your my_gem.rb file.

module MyGem
class Calculator
def self.add(a,b)
puts (a+b)

The root file inside “lib” will usually match the name of the gem.

Generate the Gem File:
Now we generate the gem file so that we can use this code in other ruby program.
Run this command on your terminal to generate gem file.

gem build my_gem.gemspec

Installation of My Gem:
Now we have our gem file, we can use RubyGems to install gem on our system.

gem install my_gem

Add this Gem File to another Ruby File:
Create a file.

vi addition.rb

Copy the code below in your addition.rb file.

require 'my_gem'

Run addition.rb:

ruby addition.rb

You should see the following output:





SDE 2 at, Directi

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Log Analytics Solutions

A Product Manager Wireframes

Azure Privileged Identity Management

Why and how we wrote a compiler in Rust (blog post series 1/X): the context

Hyperledger Fabric Damn ImplicitMetaPolicy

Test post!

Adventures with Content Delivery (mostly CloudFront) Optimizations

Ecommerce Template Free Download

Ecommerce Template Free Download

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shivam Sinha

Shivam Sinha

SDE 2 at, Directi

More from Medium

Rails User Session Handling using Redis

How To Integrate The Stripe Into Your Rails Application?

Why do I write gems for common API wrappers in my projects?

CircleCI Setup For Ruby On Rails Project