| name | ruby-stdlib |
| description | This skill should be used when the user asks about "Ruby standard library", "stdlib", "FileUtils", "JSON", "CSV", "YAML", "Net::HTTP", "URI", "OpenStruct", "Struct", "Set", "Date", "Time", "Pathname", "StringIO", "Tempfile", "Logger", "OptionParser", or needs guidance on Ruby's built-in libraries. |
| version | 1.0.0 |
Ruby Standard Library
Guide to Ruby's built-in standard library modules and classes.
File Operations
FileUtils
require "fileutils"
FileUtils.cp("source.txt", "dest.txt")
FileUtils.cp_r("source_dir", "dest_dir")
FileUtils.mv("old.txt", "new.txt")
FileUtils.rm("file.txt")
FileUtils.rm_rf("directory")
FileUtils.mkdir_p("path/to/nested/dir")
FileUtils.chmod(0755, "script.sh")
FileUtils.chmod_R(0644, "directory")
FileUtils.touch("file.txt")
Pathname
require "pathname"
path = Pathname.new("/home/user/project/lib/file.rb")
path.dirname
path.basename
path.extname
path.basename(".rb")
path.exist?
path.directory?
path.file?
path.read
path.write("content")
path.readlines
path.parent
path.join("sub", "file.txt")
path.relative_path_from(Pathname.new("/home/user"))
Pathname.glob("**/*.rb").each do |file|
puts file
end
Tempfile and StringIO
require "tempfile"
require "stringio"
Tempfile.create("prefix") do |file|
file.write("data")
file.rewind
file.read
end
tempfile = Tempfile.new(["report", ".csv"])
tempfile.path
tempfile.close
io = StringIO.new
io.puts "line 1"
io.puts "line 2"
io.string
io.rewind
io.readline
io = StringIO.new("existing content")
io.read
Data Formats
JSON
require "json"
data = JSON.parse('{"name": "Alice", "age": 30}')
data["name"]
data = JSON.parse('{"name": "Alice"}', symbolize_names: true)
data[:name]
{ name: "Alice", scores: [95, 87, 92] }.to_json
JSON.pretty_generate({ name: "Alice", nested: { key: "value" } })
File.open("large.json") do |file|
JSON.parse(file)
end
CSV
require "csv"
CSV.foreach("data.csv", headers: true) do |row|
puts row["name"]
puts row["email"]
end
data = CSV.parse("name,age\nAlice,30\nBob,25", headers: true)
data.each do |row|
puts "#{row['name']} is #{row['age']}"
end
rows = CSV.read("data.csv", headers: true)
CSV.open("output.csv", "w") do |csv|
csv << ["name", "email"]
csv << ["Alice", "alice@example.com"]
csv << ["Bob", "bob@example.com"]
end
csv_string = CSV.generate do |csv|
csv << ["header1", "header2"]
csv << ["value1", "value2"]
end
CSV.foreach("data.csv",
headers: true,
header_converters: :symbol,
converters: :numeric
) do |row|
row[:age]
end
YAML
require "yaml"
config = YAML.load_file("config.yml")
data = YAML.safe_load(<<~YAML)
database:
host: localhost
port: 5432
features:
- auth
- api
YAML
{ name: "Alice", tags: %w[ruby rails] }.to_yaml
YAML.safe_load(yaml_string, permitted_classes: [Date, Time])
YAML.safe_load(yaml_string, aliases: true)
Networking
Net::HTTP
require "net/http"
require "uri"
require "json"
uri = URI("https://api.example.com/users")
response = Net::HTTP.get_response(uri)
response.body
uri = URI("https://api.example.com/users")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer token"
request["Accept"] = "application/json"
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
uri = URI("https://api.example.com/users")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path)
request["Content-Type"] = "application/json"
request.body = { name: "Alice", email: "alice@example.com" }.to_json
response = http.request(request)
case response
when Net::HTTPSuccess
JSON.parse(response.body)
when Net::HTTPRedirection
when Net::HTTPClientError
raise "Client error: #{response.code}"
when Net::HTTPServerError
raise "Server error: #{response.code}"
end
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 5
http.read_timeout = 10
URI
require "uri"
uri = URI("https://user:pass@example.com:8080/path?query=value#fragment")
uri.scheme
uri.userinfo
uri.host
uri.port
uri.path
uri.query
uri.fragment
uri = URI::HTTPS.build(
host: "api.example.com",
path: "/v1/users",
query: URI.encode_www_form(page: 1, limit: 10)
)
URI.decode_www_form("name=Alice&age=30")
URI.decode_www_form("name=Alice&age=30").to_h
Data Structures
Struct
Person = Struct.new(:name, :age, keyword_init: true) do
def adult?
age >= 18
end
end
person = Person.new(name: "Alice", age: 30)
person.name
person.adult?
person.to_h
Point = Struct.new(:x, :y)
point = Point.new(10, 20)
OpenStruct
require "ostruct"
person = OpenStruct.new(name: "Alice", age: 30)
person.name
person.email = "alice@example.com"
person.email
person.to_h
data = { host: "localhost", port: 3000 }
config = OpenStruct.new(data)
config.host
Set
require "set"
set = Set.new([1, 2, 3])
set.add(4)
set.add(2)
set.to_a
set.include?(2)
set.member?(5)
a = Set[1, 2, 3]
b = Set[2, 3, 4]
a | b # Union: Set[1, 2, 3, 4]
a & b # Intersection: Set[2, 3]
a - b # Difference: Set[1]
a ^ b # Symmetric difference: Set[1, 4]
a.subset?(b) # => false
a.superset?(b) # => false
# SortedSet (requires 'sorted_set' gem in Ruby 3+)
Date and Time
Date
require "date"
today = Date.today
date = Date.new(2024, 12, 25)
date = Date.parse("2024-12-25")
date = Date.strptime("25/12/2024", "%d/%m/%Y")
date.year
date.month
date.day
date.wday
date.monday?
date + 7
date >> 1
date << 1
date.next_month
date.prev_year
date.strftime("%Y-%m-%d")
date.strftime("%B %d, %Y")
(Date.today..Date.today + 7).each { |d| puts d }
Time
now = Time.now
utc = Time.now.utc
time = Time.new(2024, 12, 25, 10, 30, 0)
time = Time.parse("2024-12-25 10:30:00")
time.hour
time.min
time.sec
time.zone
time.utc?
time + 3600
time - 86400
time.to_i
Time.at(1703505000)
time.strftime("%Y-%m-%d %H:%M:%S")
time.iso8601
Logging
Logger
require "logger"
logger = Logger.new($stdout)
logger = Logger.new("application.log")
logger = Logger.new("app.log", "daily")
logger.level = Logger::INFO
logger.debug("Debug message")
logger.info("Info message")
logger.warn("Warning message")
logger.error("Error message")
logger.fatal("Fatal message")
logger.debug { "Expensive debug: #{expensive_computation}" }
logger.formatter = proc do |severity, datetime, progname, msg|
"[#{datetime.strftime('%Y-%m-%d %H:%M:%S')}] #{severity}: #{msg}\n"
end
logger.info("Processing") { "order_id=123" }
CLI Parsing
OptionParser
require "optparse"
options = { verbose: false, output: "result.txt" }
OptionParser.new do |opts|
opts.banner = "Usage: script.rb [options]"
opts.on("-v", "--verbose", "Enable verbose output") do
options[:verbose] = true
end
opts.on("-o", "--output FILE", "Output file") do |file|
options[:output] = file
end
opts.on("-n", "--count NUM", Integer, "Number of items") do |n|
options[:count] = n
end
opts.on("-t", "--type TYPE", %w[json xml csv], "Output type") do |type|
options[:type] = type
end
opts.on("-h", "--help", "Show help") do
puts opts
exit
end
end.parse!
files = ARGV