Rails Insights

How to Write a Simple CLI Tool with Ruby

Introduction

Ruby is a versatile programming language that can be used to create command-line interface (CLI) tools. In this article, we will walk you through the process of creating a simple CLI tool using Ruby. Whether you are a beginner or an experienced Ruby developer, this guide will help you get started with building your own CLI tool.

Prerequisites

Before we dive into creating a CLI tool with Ruby, make sure you have Ruby installed on your system. You can check if Ruby is installed by running the following command in your terminal:

ruby -v

If Ruby is not installed, you can download and install it from the official Ruby website: https://www.ruby-lang.org/en/downloads/

Step 1: Create a New Ruby File

Open your favorite text editor and create a new Ruby file for your CLI tool. You can name the file anything you like, but for this example, we will name it cli_tool.rb.

touch cli_tool.rb

Step 2: Define the Command Line Interface

In your cli_tool.rb file, start by defining the command line interface for your tool. You can use the OptionParser class from the Ruby standard library to parse command line options and arguments.

require 'optparse'

options = {}

OptionParser.new do |opts|
  opts.banner = "Usage: cli_tool [options]"

  opts.on("-h", "--help", "Prints this help") do
    puts opts
    exit
  end

  opts.on("-n", "--name NAME", "Specify a name") do |name|
    options[:name] = name
  end
end.parse!

Step 3: Implement the Functionality

Next, implement the functionality of your CLI tool based on the options and arguments provided by the user. For example, you can greet the user with the specified name.

if options[:name]
  puts "Hello, #{options[:name]}!"
else
  puts "Hello, World!"
end

Step 4: Make the File Executable

Make the cli_tool.rb file executable by adding a shebang line at the top of the file.

#!/usr/bin/env ruby

# Your code here

Then, make the file executable by running the following command:

chmod +x cli_tool.rb

Step 5: Test Your CLI Tool

Now that you have created your CLI tool, it's time to test it. Run the following command in your terminal to see the help message:

./cli_tool.rb -h

You can also run the CLI tool with different options and arguments to see how it behaves:

./cli_tool.rb -n Alice

Conclusion

Congratulations! You have successfully created a simple CLI tool with Ruby. This is just the beginning – you can further enhance your tool by adding more options, implementing additional functionality, and customizing the user experience. Happy coding!

Published: May 30, 2024

© 2024 RailsInsights. All rights reserved.