Ruby 3 cheatsheet

Ruby 3: Errors and files

7 common Ruby 3 tasks.

Rescue exceptions

Handle errors with begin/rescue/ensure. Rescue specific classes, not Exception.

begin
  Integer("abc")
rescue ArgumentError => e
  puts "bad number: #{e.message}"
ensure
  puts "always runs"
end

Raise a custom error

Subclass StandardError for your own exceptions, then raise and rescue it.

class ValidationError < StandardError; end

begin
  raise ValidationError, "name is required"
rescue ValidationError => e
  puts e.message
end

Read a file

Read a whole file, or iterate lines without loading it all.

text = File.read("data.txt")
File.foreach("data.txt") { |line| puts line }

Write a file

Write text, with the file closed automatically at the end of the block.

File.open("out.txt", "w") { |f| f.puts "hello" }

Work with JSON

Convert between Ruby hashes and JSON text.

require "json"

text = JSON.generate({ name: "Ada", tags: ["a", "b"] })
data = JSON.parse(text, symbolize_names: true)

Use a Set

A collection of unique values with fast membership tests.

require "set"

seen = Set.new
seen << 1 << 2 << 1
puts seen.size

Write a test

A Minitest test, which ships with Ruby.

require "minitest/autorun"

class MathTest < Minitest::Test
  def test_addition
    assert_equal 4, 2 + 2
  end
end

Was this page helpful?