RbRuby

Ruby: More snippets – code examples

Contents

begin / rescue / ensure

Error handling#rescue#exception#ensureCompare in all languages
Use case: Guard user input or network access without the program crashing.
begin
  Integer("abc")
rescue ArgumentError => e
  puts "Error: #{e.message}"
ensure
  puts "Cleaning up"
end

Integer("abc") raises ArgumentError (unlike "abc".to_i, which silently returns 0). ensure always runs – ideal for closing resources.

Custom Error Class with retry

Error handling#raise#rescue#retry#exception
Use case: Name domain errors unambiguously and repeat flaky calls (network).
class ZuWenigGuthaben < StandardError
  def initialize(fehlt)
    super("Missing #{fehlt} EUR")
  end
end

def abheben(saldo, betrag)
  raise ZuWenigGuthaben.new(betrag - saldo) if betrag > saldo
  saldo - betrag
end

begin
  abheben(50, 80)
rescue ZuWenigGuthaben => e
  puts "#{e.class}: #{e.message}"
end

versuche = 0
begin
  versuche += 1
  raise "Connection lost" if versuche < 3
  puts "Works after #{versuche} attempts"
rescue
  retry if versuche < 3
end

Custom classes inherit from StandardError. retry jumps back to the start of the begin block. Always set an upper limit, otherwise an infinite loop results.

Write and Read a File

Files#file#read file#foreachCompare in all languages
Use case: Save logs, configurations or text data and load them again.
File.write("notizen.txt", "Line 1\nLine 2\n")
File.foreach("notizen.txt") do |zeile|
  puts zeile.chomp
end

File.write creates the file, File.foreach reads it line by line (memory-friendly even for large files). chomp removes the line break.

Reading and Writing JSON

Files#json#parse#generate
Use case: Exchange data with web APIs or other programs, read configuration files.
require "json"

daten = { name: "Ada", sprachen: ["Ruby", "C"], aktiv: true }
text = JSON.pretty_generate(daten)
puts text
zurueck = JSON.parse(text, symbolize_names: true)
puts zurueck[:sprachen].last

begin
  JSON.parse("{kaputt")
rescue JSON::ParserError
  puts "Invalid JSON"
end

JSON.parse returns a hash (with symbol keys if symbolize_names: true), JSON.generate or pretty_generate produces text. Invalid JSON raises JSON::ParserError.

Editing and Formatting Strings

Strings#string#gsub#format#scan
Use case: Clean up input, reshape texts and print prices or tables.
titel = "  hello beautiful world  "
puts titel.strip.split.map(&:capitalize).join(" ")
puts titel.strip.gsub(/\s+/, "-")
puts "Price: %.2f EUR" % 1234.5
puts format("%-8s|%5d|", "Ada", 42)
puts "ruby" * 3, "ruby".center(10, "*")
puts "Ruby is beautiful".scan(/\w+/).size

split, map(&:capitalize) and join give title case. gsub replaces via regex, format and % format. Output includes Hello Beautiful World, hello-beautiful-world, Price: 1234.50 EUR.

HTTP Request with Net::HTTP

Networking#http#net/http#api#json
Use case: Fetch data from a web API, e.g. weather, GitHub or payment services.
require "net/http"
require "json"

uri = URI("https://api.github.com/repos/ruby/ruby")
antwort = Net::HTTP.get_response(uri)
if antwort.is_a?(Net::HTTPSuccess)
  daten = JSON.parse(antwort.body)
  puts "#{daten['full_name']} has #{daten['stargazers_count']} stars"
else
  puts "Error: #{antwort.code}"
end

Net::HTTP is part of the standard library. Always check the status code. In larger projects you use gems like faraday or httparty.

Gemfile with Groups

Tools#bundler#gemfile#gem
Use case: Define the dependencies of a project reproducibly (web, tests, development).
source "https://rubygems.org"

ruby ">= 3.2"

gem "sinatra", "~> 4.0"
gem "sqlite3"

group :development, :test do
  gem "minitest"
  gem "rubocop", require: false
end

~> 4.0 allows >= 4.0 and < 5.0. bundle install creates Gemfile.lock, bundle exec runs commands with exactly these versions. Groups separate test dependencies from production dependencies.

Rails: Model with Validation

Rails#rails#activerecord#validation
Use case: Map database tables as classes – including rules and associations.
# app/models/article.rb
class Article < ApplicationRecord
  has_many :comments, dependent: :destroy

  validates :title, presence: true, length: { minimum: 3 }
  validates :slug, uniqueness: true

  scope :recent, -> { order(created_at: :desc) }
  scope :published, -> { where(published: true) }

  def kurztext
    body.to_s.truncate(100)
  end
end

# Usage, e.g. in the Rails console (bin/rails console)
Article.published.recent.limit(5).each { |a| puts a.title }
artikel = Article.new(title: "Hi")
artikel.valid?        # false
artikel.errors.full_messages

Requires a Rails app. Validations run before saving, scopes are reusable queries. where conditions with a hash are protected against SQL injection.