How to Create a Gem in Ruby: Step-by-Step Guide
To create a gem in Ruby, use
bundle gem your_gem_name to generate the basic structure and gemspec file. Then, add your Ruby code inside the lib folder, update the gemspec, and build the gem with gem build your_gem_name.gemspec.Syntax
The basic command to create a Ruby gem is bundle gem your_gem_name. This command creates a folder named your_gem_name with the following parts:
your_gem_name.gemspec: The gem specification file describing your gem.lib/: Folder where your Ruby code lives.README.md: Documentation file.Gemfile: For managing dependencies.
You then edit the gemspec to set metadata like version, author, and summary.
bash
bundle gem your_gem_name
Example
This example shows how to create a simple gem named greet that provides a greeting method.
ruby
bundle gem greet
# Navigate to the gem folder
cd greet
# In lib/greet.rb
module Greet
def self.hello(name)
"Hello, #{name}!"
end
end
# Build the gem
gem build greet.gemspec
# Install the gem locally
gem install ./greet-0.1.0.gem
# Use the gem in IRB
require 'greet'
puts Greet.hello('Friend')Output
Hello, Friend!
Common Pitfalls
Common mistakes when creating gems include:
- Not updating the
gemspecfile with correct metadata likesummaryandauthors. - Forgetting to require your main file in the gemspec's
require_paths. - Placing code outside the
libfolder, which prevents it from loading properly. - Not building the gem before installing or publishing.
Always test your gem locally before publishing.
ruby
## Wrong gemspec snippet # spec.summary = '' # Empty summary causes warnings ## Correct gemspec snippet spec.summary = 'A simple greeting gem' spec.authors = ['Your Name']
Quick Reference
| Step | Command / Action |
|---|---|
| Create gem skeleton | bundle gem your_gem_name |
| Write code | Add Ruby files inside lib/ |
| Edit gemspec | Update metadata and dependencies |
| Build gem | gem build your_gem_name.gemspec |
| Install gem locally | gem install ./your_gem_name-version.gem |
| Publish gem | gem push your_gem_name-version.gem |
Key Takeaways
Use 'bundle gem your_gem_name' to create the gem structure quickly.
Put your Ruby code inside the 'lib' folder for proper loading.
Always update the gemspec file with accurate metadata before building.
Build and install your gem locally to test before publishing.
Follow the quick reference steps to create, build, and publish your gem.