Ruby on Rails - Ruby Standard Library
Introduction
The Ruby standard library is a collection of classes and modules that come with the Ruby installation. It provides a wide range of functionalities, from handling file I/O to working with dates and times. This guide will provide an overview of some of the most commonly used features of the Ruby standard library.
Key Points:
- The Ruby standard library includes a variety of useful classes and modules.
- Commonly used features include file handling, date and time manipulation, and networking.
- This guide provides an overview of some of the most frequently used parts of the Ruby standard library.
File Handling
Ruby provides several classes for handling file operations, such as reading from and writing to files. Here are some examples:
# Write to a file
File.open('example.txt', 'w') do |file|
file.puts 'Hello, world!'
end
# Read from a file
File.open('example.txt', 'r') do |file|
content = file.read
puts content # Output: Hello, world!
end
In this example, a file is opened for writing, some text is written to it, and then the file is read and its contents are printed to the console.
Date and Time
Ruby provides classes for working with dates and times. Here are some examples:
# Get the current date and time
now = Time.now
puts now # Output: current date and time
# Create a specific date
date = Date.new(2023, 7, 12)
puts date # Output: 2023-07-12
# Parse a date string
parsed_date = Date.parse('2023-07-12')
puts parsed_date # Output: 2023-07-12
In this example, the current date and time are retrieved, a specific date is created, and a date string is parsed into a date object.
JSON Handling
Ruby includes support for parsing and generating JSON. Here are some examples:
# Require the JSON library
require 'json'
# Parse a JSON string
json_string = '{"name": "Alice", "age": 30}'
parsed_data = JSON.parse(json_string)
puts parsed_data['name'] # Output: Alice
# Generate a JSON string
data = { name: 'Bob', age: 25 }
json_output = JSON.generate(data)
puts json_output # Output: {"name":"Bob","age":25}
In this example, a JSON string is parsed into a Ruby hash, and a Ruby hash is generated into a JSON string.
Networking
Ruby provides several classes for handling networking tasks, such as making HTTP requests. Here are some examples:
# Require the net/http library
require 'net/http'
# Make a GET request
uri = URI('https://api.example.com/data')
response = Net::HTTP.get(uri)
puts response
# Make a POST request
uri = URI('https://api.example.com/data')
response = Net::HTTP.post_form(uri, 'param1' => 'value1', 'param2' => 'value2')
puts response.body
In this example, a GET request and a POST request are made to a specified URI, and the responses are printed to the console.
Command-Line Options
Ruby provides libraries for handling command-line options. Here is an example using OptionParser
:
# Require the OptionParser library
require 'optparse'
# Define options
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: example.rb [options]"
opts.on("-n", "--name NAME", "Name") do |v|
options[:name] = v
end
opts.on("-a", "--age AGE", "Age") do |v|
options[:age] = v
end
end.parse!
# Output options
puts "Name: #{options[:name]}"
puts "Age: #{options[:age]}"
In this example, command-line options for a name and age are defined and parsed, and the values are printed to the console.
Threading
Ruby provides support for threading, allowing you to run multiple operations concurrently. Here is an example:
# Create a new thread
thread = Thread.new do
5.times do |i|
puts "Thread: #{i}"
sleep 1
end
end
# Main thread
5.times do |i|
puts "Main: #{i}"
sleep 1
end
# Wait for the thread to finish
thread.join
In this example, a new thread is created to run concurrently with the main thread, and both threads print output to the console.
Conclusion
The Ruby standard library provides a wealth of functionalities that make it easier to handle common programming tasks. This guide provided an overview of some of the most commonly used features, including file handling, date and time manipulation, JSON handling, networking, command-line options, and threading. With these tools, you can effectively build and manage your Ruby applications.