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.
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}"
add
, subtract
, multiply
, or divide
as the operation.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)
.jpg
, .txt
).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
YOUR_API_KEY_HERE
with a valid OpenWeather API key.