Ruby Command-Line Interface Examples

Explore practical examples of Ruby command-line interfaces to enhance your programming skills.
By Jamie

Introduction to Ruby Command-Line Interfaces

Ruby is a versatile programming language that allows developers to create powerful command-line interfaces (CLI) to interact with users, automate tasks, or manage system resources. In this article, we will explore three practical examples of Ruby command-line interfaces that demonstrate different functionalities and use cases.

Example 1: Simple Calculator CLI

Context

This example showcases a basic command-line calculator that can perform addition, subtraction, multiplication, and division. It accepts user input for the operation and numbers, making it a useful tool for quick calculations.

# Simple Calculator CLI

def calculator(operation, num1, num2)
  case operation.downcase
  when 'add'
    num1 + num2
  when 'subtract'
    num1 - num2
  when 'multiply'
    num1 * num2
  when 'divide'
    num1 / num2
  else
    "Invalid operation!"
  end
end

puts 'Welcome to the Ruby Calculator!'
puts 'Enter operation (add, subtract, multiply, divide):'
operation = gets.chomp

puts 'Enter first number:'
num1 = gets.chomp.to_f

puts 'Enter second number:'
num2 = gets.chomp.to_f

result = calculator(operation, num1, num2)
puts "The result is: \\#{result}"

Notes

  • Users can enter add, subtract, multiply, or divide as the operation.
  • Ensure valid numeric inputs to avoid exceptions.

Example 2: File Organizer CLI

Context

This example demonstrates a command-line tool that organizes files in a specified directory by moving them into subfolders based on their file extensions. It’s beneficial for maintaining file organization without manually sorting files.

# File Organizer CLI

require 'fileutils'

def organize_files(directory)
  Dir.foreach(directory) do |file|
    next if file == '.' || file == '..'
    ext = File.extname(file)[1..-1] # Get file extension without dot
    folder = File.join(directory, ext)
    FileUtils.mkdir_p(folder) unless Dir.exist?(folder)
    FileUtils.mv(File.join(directory, file), folder)
    puts "Moved \\#{file} to \\#{folder}"
  end
end

puts 'Welcome to the File Organizer!'
puts 'Enter the directory path to organize:'
directory = gets.chomp

organize_files(directory)

Notes

  • The script creates subfolders for each file extension (e.g., .jpg, .txt).
  • Users must have the appropriate permissions to read and write in the specified directory.

Example 3: Weather Fetcher CLI

Context

This example illustrates a command-line application that fetches and displays weather information using a public API. It demonstrates how to make HTTP requests and parse JSON data, providing a practical use of APIs in Ruby.

# Weather Fetcher CLI

require 'net/http'
require 'json'

def fetch_weather(city)
  api_key = 'YOUR_API_KEY_HERE'
  url = "http://api.openweathermap.org/data/2.5/weather?q=\#{city}&appid=\#{api_key}&units=metric"
  response = Net::HTTP.get(URI(url))
  JSON.parse(response)
end

puts 'Welcome to the Weather Fetcher!'
puts 'Enter the city name:'
city = gets.chomp

weather_data = fetch_weather(city)

if weather_data['cod'] == 200
  puts "Current temperature in \\#{city}: \\#{weather_data['main']['temp']}°C"
else
  puts 'City not found!'
end

Notes

  • Replace YOUR_API_KEY_HERE with a valid OpenWeather API key.
  • Error handling can be enhanced to manage network issues or invalid responses.