Exploring Ruby’s Standard Library and Building and Using Gems — Ruby Deep Dive [06]
Standard Library
Ruby’s standard library is a treasure trove of useful modules and classes that can save you time and effort. Let’s explore some essential standard libraries with practical examples and use cases.
File Operations
The File
and Dir
classes in Ruby provide methods to perform various file and directory operations.
File Class
Reading and Writing Files
# Reading from a file
File.open('example.txt', 'r') do |file|
content = file.read
puts content
end
# Writing to a file
File.open('example.txt', 'w') do |file|
file.write("Hello, world!")
end
File Existence and Properties
# Check if a file exists
puts File.exist?('example.txt') # => true or false
# Get file size
puts File.size('example.txt') # => file size in bytes
# Get file type
puts File.ftype('example.txt') # => "file", "directory", etc.
File Manipulation
# Rename a file
File.rename('example.txt', 'new_example.txt')
# Delete a file
File.delete('new_example.txt')
Dir Class
Listing Directory Contents
# List all files and directories
Dir.foreach('.') do |entry|
puts entry
end
# Get an array of files and directories
entries = Dir.entries('.')
puts entries
Creating and Removing Directories
# Create a directory
Dir.mkdir('new_directory')
# Remove a directory
Dir.rmdir('new_directory')
System Commands
Ruby provides several ways to execute system commands from within a Ruby script.
system
Method
The system
method executes a command in a subshell, returning true
if the command was successful, and false
otherwise.
if system('ls')
puts 'Command succeeded'
else
puts 'Command failed'
end
Backticks and %x
Backticks (`
) and the %x
syntax execute a command and return the output as a string.
output = `ls`
puts output
# or using %x
output = %x(ls)
puts output
exec
Method
The exec
method replaces the current process with the specified command. It does not return.
exec('ls')
puts 'This will not be printed'
Environment Variables
Ruby allows you to access and manipulate environment variables using the ENV
hash.
Accessing Environment Variables
# Access an environment variable
puts ENV['HOME'] # => "/home/user"
# Check if an environment variable exists
puts ENV.key?('HOME') # => true or false
Setting Environment Variables
# Set an environment variable
ENV['MY_VARIABLE'] = 'my_value'
puts ENV['MY_VARIABLE'] # => "my_value"
Deleting Environment Variables
# Delete an environment variable
ENV.delete('MY_VARIABLE')
puts ENV['MY_VARIABLE'] # => nil
System Information
The RbConfig
module provides information about the Ruby environment.
Getting Ruby Configuration
require 'rbconfig'
# Get Ruby version
puts RbConfig::CONFIG['RUBY_PROGRAM_VERSION'] # => "2.7.0"
# Get host operating system
puts RbConfig::CONFIG['host_os'] # => "linux-gnu", "darwin18", etc.
# Get Ruby executable path
puts RbConfig::CONFIG['bindir'] # => "/usr/local/bin"
Handling Time and Date
Ruby provides the Time
and Date
classes to work with dates and times.
Time Class
Current Time
# Get the current time
current_time = Time.now
puts current_time # => 2024-07-18 10:15:30 +0000
Creating Time Objects
# Create a specific time
specific_time = Time.new(2024, 7, 18, 10, 0, 0, "+00:00")
puts specific_time # => 2024-07-18 10:00:00 +0000
Time Arithmetic
# Add seconds to a time
later_time = current_time + 60 # 60 seconds later
puts later_time
# Subtract times
time_difference = later_time - current_time
puts time_difference # => 60.0
Date Class
Creating Date Objects
require 'date'
# Create a specific date
specific_date = Date.new(2024, 7, 18)
puts specific_date # => 2024-07-18
Date Arithmetic
# Add days to a date
later_date = specific_date + 10
puts later_date # => 2024-07-28
# Subtract dates
date_difference = later_date - specific_date
puts date_difference # => 10
Net::HTTP
The Net::HTTP
module allows you to make HTTP requests and handle responses.
Example:
require 'net/http'
require 'uri'
uri = URI.parse("http://www.example.com/")
response = Net::HTTP.get_response(uri)
puts response.body
JSON
The JSON
module provides methods to parse and generate JSON data.
Example:
require 'json'
# Parsing JSON
json_data = '{"name": "John", "age": 30}'
parsed_data = JSON.parse(json_data)
puts parsed_data["name"]
# Generating JSON
hash_data = { name: "Jane", age: 25 }
json_string = JSON.generate(hash_data)
puts json_string
CSV
The CSV
module makes it easy to read from and write to CSV files.
Example:
require 'csv'
# Reading a CSV file
CSV.foreach('data.csv', headers: true) do |row|
puts row['Name']
end
# Writing to a CSV file
CSV.open('data.csv', 'w') do |csv|
csv << ["Name", "Age"]
csv << ["Alice", 30]
csv << ["Bob", 25]
end
Building Gems
Creating and publishing Ruby gems allows you to share your code with the Ruby community.
Structure of a Ruby Gem
A typical gem structure looks like this:
my_gem/
├── lib/
│ └── my_gem.rb
├── test/
│ └── test_my_gem.rb
├── my_gem.gemspec
└── README.md
Creating and Publishing a Gem
- Create the Gem Structure:
bundle gem my_gem
2. Edit the Gemspec: Modify the my_gem.gemspec
file to include gem details such as name, version, and dependencies.
3. Write the Code: Add your code to the lib/my_gem.rb
file.
4. Build the Gem:
gem build my_gem.gemspec
5. Publish the Gem:
gem push my_gem-0.1.0.gem
Managing Dependencies with Bundler
Bundler is a tool for managing gem dependencies in your Ruby projects.
Example:
# Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 6.0'
gem 'puma', '~> 4.1'
# Install dependencies
bundle install
Using Gems
Gems are packages of Ruby code that can be easily shared and reused. Let’s see how to install and use popular gems.
Installing and Using Popular Gems
- Installing a Gem:
gem install nokogiri
2. Using a Gem:
require 'nokogiri'
html = "<html><body><h1>Hello, world!</h1></body></html>"
doc = Nokogiri::HTML(html) puts doc.at_css('h1').text
Best Practices for Managing Dependencies
- Use a Gemfile: Always use a
Gemfile
to specify your project's dependencies. - Version Pinning: Specify gem versions to avoid breaking changes.
- Regular Updates: Regularly update your gems to get the latest features and security fixes.
- Isolate Dependencies: Use Bundler to manage gem dependencies and avoid conflicts.