0
0
Rubyprogramming~10 mins

Creating a gem basics in Ruby

Choose your learning style9 modes available
Introduction

A Ruby gem is a package that holds code you can share and reuse easily. Creating a gem helps you organize your code and share it with others.

You want to share your Ruby code with friends or other developers.
You have a set of useful methods or classes you want to reuse in many projects.
You want to publish your code so others can install it easily.
You want to keep your code organized in a neat package.
You want to manage versions of your code for updates.
Syntax
Ruby
gem_name/
  lib/
    gem_name.rb
  gem_name.gemspec
  README.md
  Rakefile

The gem folder has a special file called gem_name.gemspec that describes your gem.

The lib folder holds your Ruby code files.

Examples
This shows how to build and install your gem locally.
Ruby
mkdir my_gem
cd my_gem
gem build my_gem.gemspec
gem install ./my_gem-0.1.0.gem
This is a simple gemspec file that describes your gem's name, version, author, and files.
Ruby
# my_gem.gemspec
Gem::Specification.new do |spec|
  spec.name        = "my_gem"
  spec.version     = "0.1.0"
  spec.summary     = "A simple example gem"
  spec.authors     = ["Your Name"]
  spec.files       = Dir["lib/**/*.rb"]
end
Sample Program

This example shows the basic steps to create a gem named hello_gem that has a method to say hello. You build and install it locally, then use it in Ruby code.

Ruby
# Step 1: Create a folder named 'hello_gem'
# Step 2: Inside 'hello_gem', create 'hello_gem.gemspec' with:
#
# Gem::Specification.new do |spec|
#   spec.name        = "hello_gem"
#   spec.version     = "0.1.0"
#   spec.summary     = "A gem that says hello"
#   spec.authors     = ["You"]
#   spec.files       = Dir["lib/**/*.rb"]
# end
#
# Step 3: Create folder 'lib' inside 'hello_gem'
# Step 4: Inside 'lib', create 'hello_gem.rb' with:
module HelloGem
  def self.say_hello
    "Hello from the gem!"
  end
end

# Step 5: Build the gem (run in terminal):
# gem build hello_gem.gemspec

# Step 6: Install the gem locally (run in terminal):
# gem install ./hello_gem-0.1.0.gem

# Step 7: Use the gem in Ruby code:
require 'hello_gem'
puts HelloGem.say_hello
OutputSuccess
Important Notes

Always keep your gemspec file updated with correct info.

Use gem build to create the gem package file.

Test your gem locally before sharing it.

Summary

A gem is a reusable Ruby package for sharing code.

Creating a gem involves making a gemspec file and organizing code in lib.

You build and install the gem to use it in projects.