Ruby Standard Library

Built-in Ruby libraries and modules

📚 What is the Standard Library?

Ruby's Standard Library is a collection of built-in modules and classes that come with Ruby. These libraries provide functionality for common tasks like file handling, networking, date manipulation, and more without requiring external gems.


# Use standard library modules
require 'date'
require 'json'

today = Date.today
puts today.strftime('%B %d, %Y')
                                    

Output:

January 15, 2024

Popular Standard Libraries

📅

Date & Time

Work with dates and times

require 'date'
📄

JSON

Parse and generate JSON

require 'json'
🌐

Net::HTTP

Make HTTP requests

require 'net/http'
📁

FileUtils

File operations utilities

require 'fileutils'

🔹 Date and Time Library

The Date and Time libraries provide classes for working with dates, times, and durations. Use them to parse dates, format output, calculate differences, and perform date arithmetic operations.

require 'date'
require 'time'

# Create dates
today = Date.today
puts today  # => 2024-01-15

# Parse dates
birthday = Date.parse('1990-05-20')
puts birthday.year  # => 1990

# Date arithmetic
next_week = today + 7
puts next_week

# Format dates
puts today.strftime('%A, %B %d, %Y')
# => Monday, January 15, 2024

# Time operations
now = Time.now
puts now.strftime('%I:%M %p')  # => 02:30 PM

Output:

2024-01-15
1990
2024-01-22
Monday, January 15, 2024
02:30 PM

🔹 JSON Library

The JSON library allows you to parse JSON strings into Ruby objects and convert Ruby objects into JSON format. Essential for working with APIs and data interchange between systems.

require 'json'

# Parse JSON string
json_string = '{"name": "Alice", "age": 30}'
data = JSON.parse(json_string)
puts data['name']  # => Alice
puts data['age']   # => 30

# Convert Ruby to JSON
person = { name: 'Bob', age: 25, city: 'NYC' }
json = JSON.generate(person)
puts json
# => {"name":"Bob","age":25,"city":"NYC"}

# Pretty print JSON
puts JSON.pretty_generate(person)
# => {
#      "name": "Bob",
#      "age": 25,
#      "city": "NYC"
#    }

Output:

Alice
30
{"name":"Bob","age":25,"city":"NYC"}

🔹 Net::HTTP Library

Net::HTTP provides functionality for making HTTP requests to web servers. Use it to fetch web pages, interact with APIs, and download files from the internet programmatically.

require 'net/http'
require 'uri'

# Simple GET request
uri = URI('https://api.github.com/users/github')
response = Net::HTTP.get(uri)
puts response[0..100]  # First 100 characters

# GET with response object
uri = URI('https://httpbin.org/get')
response = Net::HTTP.get_response(uri)
puts response.code        # => 200
puts response.message     # => OK
puts response.body[0..50]

# POST request
uri = URI('https://httpbin.org/post')
res = Net::HTTP.post_form(uri, 'name' => 'Ruby', 'version' => '3.2')
puts res.body

Output:

{"login":"github","id":9919,...
200
OK

🔹 FileUtils Library

FileUtils provides convenient methods for file and directory operations. It simplifies tasks like copying files, creating directories, and removing files with easy-to-use commands and options.

Common FileUtils Methods:

  • cp - Copy files
  • mv - Move/rename files
  • rm - Remove files
  • mkdir_p - Create directories
  • pwd - Print working directory
require 'fileutils'

# Create directory
FileUtils.mkdir_p('project/src')

# Copy file
FileUtils.cp('file.txt', 'backup/file.txt')

# Move file
FileUtils.mv('old.txt', 'new.txt')

# Remove file
FileUtils.rm('temp.txt')

# Remove directory
FileUtils.rm_rf('old_project')

# Current directory
puts FileUtils.pwd

Output:

/home/user/projects

🔹 Set Library

The Set library provides a collection of unique elements with fast lookup. Sets automatically remove duplicates and offer mathematical set operations like union, intersection, and difference.

require 'set'

# Create a set
numbers = Set.new([1, 2, 3, 3, 4])
puts numbers.to_a.inspect  # => [1, 2, 3, 4]

# Add elements
numbers.add(5)
numbers << 6

# Check membership
puts numbers.include?(3)  # => true

# Set operations
set1 = Set.new([1, 2, 3])
set2 = Set.new([3, 4, 5])

puts (set1 | set2).to_a.inspect  # Union: [1, 2, 3, 4, 5]
puts (set1 & set2).to_a.inspect  # Intersection: [3]
puts (set1 - set2).to_a.inspect  # Difference: [1, 2]

Output:

[1, 2, 3, 4]
true
[1, 2, 3, 4, 5]
[3]
[1, 2]

🔹 CSV Library

The CSV library makes it easy to read and write CSV (Comma-Separated Values) files. Use it to import data from spreadsheets, export reports, and work with tabular data efficiently.

require 'csv'

# Write CSV
CSV.open('users.csv', 'w') do |csv|
  csv << ['Name', 'Age', 'City']
  csv << ['Alice', 30, 'NYC']
  csv << ['Bob', 25, 'LA']
end

# Read CSV
CSV.foreach('users.csv', headers: true) do |row|
  puts "#{row['Name']} is #{row['Age']} years old"
end

# Parse CSV string
data = CSV.parse("a,b,c\n1,2,3\n4,5,6")
puts data[1][1]  # => 2

Output:

Alice is 30 years old
Bob is 25 years old
2

🧠 Test Your Knowledge

Which library is used to parse JSON in Ruby?