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
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.

Gem::Specification.new do |s|
s.name = "my_gem"
s.version = "0.0.1"
s.date = "2018-07-02"
s.summary = "My new gem"
s.authors = ["Shivam"]
s.files = ['lib/my_gem.rb']
s.require_paths = ["lib"]
end

Here s.name 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)
end
end
end

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'
MyGem::Calculator.add(4,5)

Run addition.rb:

ruby addition.rb

You should see the following output:

9

--

--

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