DEV Community

Cover image for 7 Ruby Standard libraries you should get to grips with
Pete Hawkins
Pete Hawkins

Posted on

7 Ruby Standard libraries you should get to grips with

Ruby has a lot of useful things in its Standard Library.

Learning what’s included and how to use it can be very helpful, especially when writing small scripts where you don’t want to pull in bundler and start making a Gemfile etc.

These libraries are robust, maintained by the core team and should be extremely reliable, and outlive most Ruby gems you come across.

1. Net/HTTP and open-uri

I wanted to start with something I need in most applications I build, and that’s the ability to perform an HTTP request.

In the past I have opted to use the HTTP.rb gem, but for simple tasks it’s really useful to learn Net/http or even open-uri for simple GET requests.

require "net/http"
require "json"

# Net/HTTP GET request
uri = URI("")
resp = Net::HTTP.get(uri)
json = JSON.parse(resp)
puts json["title"] # => "A New Hope"

# Net/HTTP POST request
uri = URI("")
params = {
  "name" => "Bob",
  "email" => "",
res = Net::HTTP.post_form(uri, params)
puts res.body

# Net/HTTP Full form: delete/put/patch requests
uri = URI("")

Net::HTTP.start(, uri.port) do |http|
  request = uri
  # or request = uri
  # or request = uri

  response = http.request(request) # Net::HTTPResponse object
  puts response.body
Enter fullscreen mode Exit fullscreen mode

Things are even simpler with open-uri if you only need a GET request:

require "open-uri"
require "json""") do |io|
  json = JSON.parse(
  puts json["title"] # => "A New Hope"

# or
uri = URI("")
Enter fullscreen mode Exit fullscreen mode

2. CSV

When I’m creating an admin section, I often need to export some form of reports to measure how an application is performing. Ruby has this built in and to take some data and place it into a CSV is pretty simple.

require "csv"

module CustomerExport

  def generate(customers)
    CSV.generate do |csv|
      # Define the headers
      csv << %w[id name email country_code created_at updated_at]

      # Add a new row for each customer record
      customers.each do |customer|
        csv <<

Enter fullscreen mode Exit fullscreen mode

And if you wanted to make a Rails route to download this...

module Admin
  class ExportsController < AdminBaseController
    def customers
      customers = Customer.all
      respond_to do |format|
        format.csv do
          filename = "customers-#{"%Y-%m-%d")}"
          filename += ".csv"
          headers["Content-Type"] ||= "text/csv"
          headers["Content-Disposition"] =
            "attachment; filename=\"#{filename}\""
          render plain: CustomerExport.generate(customers)
    rescue => e
      flash[:error] = "Failed to generate export: #{e.message}"
      redirect_to admin_path
Enter fullscreen mode Exit fullscreen mode

Parsing CSVs (for example: importing CSV files from users) is also built in and you can read the documentation for more on that.

3. SimpleDelegator

I like to use SimpleDelegator to add extra behaviour to ActiveRecord objects, such as having Stripe specific code wrapped up into StripeWrappedUser or something similar, this avoids placing lots of methods on your ActiveRecord object, but can then augment that class with extra functionality.

require "delegate"
require "digest"

class User <, :email)

class BillingUser < SimpleDelegator
  def billing_system_id
    Digest::SHA1.hexdigest(id.to_s + email)

bob =, "")
bob =
puts # =>
puts bob.billing_system_id # => 186da93f0b39990e034a80cc4b45c8ec253f2a1a
Enter fullscreen mode Exit fullscreen mode

4. Struct and OpenStruct

Struct is included in Ruby core, it doesn’t need required, and is the stricter of the two objects, and also much more performant.

I find it particularly useful for two things:

  1. As a value object, giving a name to some piece of data, that would otherwise be a Hash.
  2. In tests to create mock objects that can be passed in to represent fake things, like a FakeUser.
User =, :email)
alice =, "")
puts # => 1
puts # =>

# Can also be defined with additional methods
class User <, :email)
  def send_welcome_email
Enter fullscreen mode Exit fullscreen mode

OpenStruct meanwhile is a lot more flexible and can be a neat wrapper for a Hash or JSON from an API etc.

require "ostruct"

data = 5, name: "Jeffrey")

# New attributes can be set at runtime: = ""

puts # => 5
puts # => "Jeffrey"
puts # => ""
Enter fullscreen mode Exit fullscreen mode

5. PStore

PStore is a really simple key-value datastore and can be helpful when you need somewhere to store data in a non-production system (i.e. this is not a good replacement for ActiveRecord).

require "pstore"

store ="my_db.pstore")

# Write some data
store.transaction do
  store["person-1"] = { name: "Bob", email: "" }

# Read some data
store.transaction(true) do
  puts store["person-1"] # => {:name=>"Bob", :email=>""}
Enter fullscreen mode Exit fullscreen mode

6. Minitest

When working on smaller scripts, I like to pull in a test framework and make some assertions while test-driving some code.

I usually prefer RSpec when working with Rails, but it’s more effort to set up than Minitest, which comes included with Ruby.

The nice thing about Minitest, it is just Ruby – there’s nothing magical going on and it’s very easy to understand.

require "minitest/test"
require "minitest/autorun"

class APIResponse <, :error)
  def success?

class APIResponseTest < Minitest::Test
  def test_successful_responses
    resp ="Well done!", nil)
    assert resp.success?

  def test_error_responses
    resp =,"400 bad request"))
    refute resp.success?

# Running:
# ..
# Finished in 0.000957s, 2089.8640 runs/s, 2089.8640 assertions/s.
# 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
Enter fullscreen mode Exit fullscreen mode

7. Logger

Using logger can clean up a lot of your debug output when writing a script and you can then control the log level to show more/less output. Note: Use Rails.logger in Rails.

require "logger"

logger =

# Setting :warn will only show warning, error and fatal.
logger.level = :warn

# Can tweak log output to be less verbose
logger.formatter = proc do |severity, datetime, progname, msg|
  "#{severity[0...1]} #{datetime.strftime('%H:%M %b %d %Y')}: #{msg}\n"

logger.debug("Created logger") # wont be displayed in current log level"Program started") # wont be displayed in current log level
logger.warn("Nothing to do!")
logger.error("Something really bad!")

# =>
# W 14:56 Oct 22 2021: Nothing to do!
# E 14:56 Oct 22 2021: Something really bad!
Enter fullscreen mode Exit fullscreen mode

There’s plenty more in the Ruby Standard Library to get familiar with, but these 7 are things I come back to, time and time again.

Top comments (2)

phawk profile image
Pete Hawkins

Let me know if you find this useful, or if there is anything you use a lot in the standard library!

maprangsoft profile image

thank you