AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

Ruby Foundations

Core values, control flow, functions, collections, text, regular expressions, temporary files, expected errors, JSON, local modules and tests. No external data, packages or deployment.

Audience: Learners comfortable saving a source file and running an installed interpreter.

Practice: 4 to 6 hours.

Runtime and boundaries: Ruby 2.6.10p210 is installed and end-of-life upstream. Run /usr/bin/ruby followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Lessons

Pin the installed interpreter

Ruby 2.6.10 is an end-of-life branch. This pack records offline teaching behavior on this Mac, not a deployment recommendation. Ruby 3 differences and installed gems are outside its scope. Run a saved .rb with /usr/bin/ruby; the browser only exports text.

Objects, truth and conversion

Ruby variables refer to objects. Only false and nil are false-valued: 0 and empty strings are true-valued. Integer division floors toward negative infinity; fdiv produces floating-point division. Validate the intended input policy before converting text; to_i is not strict whole-input validation.

Methods and blocks

Methods return their last expression unless return is explicit. each yields values to a block, and select builds a filtered array. Keep calculations separate from output and catch only expected exceptions. The examples use ordinary Ruby 2.6 syntax, not later pattern-matching or endless-method syntax.

Collections and mutation

Arrays and hashes store object references. dup is shallow; copying the outer array does not duplicate its nested rows. Our row-copy exercise is deliberately limited to one known structure. Do not use a single mutable Hash default object as if it were independent per key.

Strings and regular expressions

Strings have an encoding. Character length and byte size differ, and character count is not grapheme count. Use Regexp.escape for literal pattern data and \A/\z for the entire string. These bounded authored patterns are not a general defense against hostile regex workloads.

Files have ownership

Only newly created temporary toy directories are writable in the file example. File.open uses an explicit UTF-8 mode and a block to close the handle. Kernel.open is avoided because pipe-prefixed input can invoke a process. No real-document path or network input is accepted.

Errors and JSON contracts

A rescue handles a selected exception, while nil can represent an absent result when documented. JSON.parse with create_additions: false produces data; it does not enforce an application schema or reject duplicate names by itself. No Marshal loading or arbitrary code evaluation is used.

Modules and tests

require_relative loads the supplied trusted companion. Code loading can execute code, so a practice folder must contain only files you control. Syntax acceptance is separate from actual program output and boundary tests. Four assertion cases demonstrate observable failure; the harness is not a sandbox for arbitrary submissions.

Reference cards

Values: Integer / Float / String / nil

Objects and absence; / differs for integer operands.

Truth: false / nil

Only these two are false-valued.

Flow: if / elsif / else / end

Choose a branch.

Blocks: each { |value| ... }

Visit each element; next skips an iteration.

Methods: def / return

Last expression is also an implicit return.

Arrays: [] / fetch / select

Ordered values; fetch can report missing indices.

Hashes: {} / fetch / keys.sort

Mappings with explicit lookup and report order.

Mutation: dup / map(&:dup)

Shallow copy only; nested objects can remain shared.

Strings: length / bytesize

Characters versus bytes, not grapheme count.

Patterns: \A / \z / Regexp.escape

Whole-string boundaries and escaped literal data.

Parsing: Integer(text, 10)

Explicit conversion; validate the intended policy.

Errors: raise / rescue ArgumentError

Signal and recover from a specific expected error.

Files: File.open(path, mode) { |f| ... }

Fixed toy path, explicit encoding, block closes handle.

Temporary: Dir.mktmpdir(prefix, ".") { ... }

Own and clean one newly created directory.

Modules: require_relative / module

Load trusted companion code and namespace methods.

JSON: JSON.generate / JSON.parse

Serialization and parsing are separate from contract checks.

Supporting configuration: Run instructions.txt
Ruby 2.6.10p210 is installed and end-of-life upstream. Run /usr/bin/ruby followed by the quoted entry filename in a new practice folder. Save companions beside the entry file. Core libraries only; no package manager is used. The browser exports text and never executes it. Syntax checks are distinct from runtime tests and are not arbitrary-code sandboxes.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

Ruby 01 - Values and interpolation

Values are objects. Integer division and floating-point division differ; interpolation formats values without changing them. nil represents absence.

name = "Ada"
minutes = 25
puts "#{name}: #{minutes} minutes"
puts "Integer division: #{minutes / 2}"
puts "Float division: #{minutes / 2.0}"
puts [minutes.class, name.class, nil.class].join(", ")

Expected:

Ada: 25 minutes
Integer division: 12
Float division: 12.5
Integer, String, NilClass

Intentionally invalid Ruby: expected interpreter syntax checker diagnostic containing syntax error. Expected rejection; not a successful program. No runtime execution follows rejection.

def unfinished(
Ruby 02 - Blocks and truth values

Only false and nil are false-valued in Ruby. Zero and empty strings are true-valued. each yields values to a block; next skips the rest of that iteration.

total = 0
[1, 2, 3, 4].each do |value|
  next if value.odd?
  total += value
end
puts "Even total: #{total}"
zero = 0
empty = ''
absent = nil
puts "Zero is #{zero ? 'true-valued' : 'false-valued'}"
puts "Empty text is #{empty ? 'true-valued' : 'false-valued'}"
puts "Nil is #{absent ? 'true-valued' : 'false-valued'}"

Expected:

Even total: 6
Zero is true-valued
Empty text is true-valued
Nil is false-valued

Intentionally invalid Ruby: expected interpreter syntax checker diagnostic containing self. Expected rejection; not a successful program. No runtime execution follows rejection.

self = 1
Ruby 03 - A method contract

The final expression is returned. Validate before calculating; rescue only the expected ArgumentError. This contract accepts Integer values, not numeric text or floating point.

def double_minutes(value)
  raise ArgumentError, 'whole minutes 0..120 required' unless
    value.is_a?(Integer) && value.between?(0, 120)
  value * 2
end
puts "Double: #{double_minutes(20)}"
begin
  double_minutes('20')
rescue ArgumentError
  puts 'Text rejected'
end

Expected:

Double: 40
Text rejected

Intentionally invalid Ruby: expected interpreter syntax checker diagnostic containing dynamic constant assignment. Expected rejection; not a successful program. No runtime execution follows rejection.

def value
  AtlasConstant = 1
end
Ruby 04 - Arrays and hash totals

An array is ordered; a hash maps keys to values. Sorting keys makes the report order deliberate. Hash.new(0) uses an immutable Integer default; do not generalize this pattern to one shared mutable default array.

sessions = [['read', 20], ['code', 30], ['read', 10]]
totals = Hash.new(0)
sessions.each { |topic, minutes| totals[topic] += minutes }
totals.keys.sort.each { |topic| puts "#{topic}: #{totals.fetch(topic)}" }
puts "Long sessions: #{sessions.select { |_, n| n >= 20 }.length}"

Expected:

code: 30
read: 30
Long sessions: 2

Intentionally invalid Ruby: expected interpreter syntax checker diagnostic containing formal argument cannot be a constant. Expected rejection; not a successful program. No runtime execution follows rejection.

def value(AtlasConstant)
end
Ruby 05 - Text, bytes and literal patterns

Source is UTF-8. String length counts characters, not grapheme clusters; bytesize counts encoded bytes. Escape a literal before placing it into a regular expression. The whole-string anchors are \A and \z; line anchors have different semantics.

label = "café"
puts "Characters: #{label.length}; UTF-8 bytes: #{label.bytesize}"
literal = 'a+b'
pattern = /\A#{Regexp.escape(literal)}\z/
puts "Literal match: #{pattern.match?('a+b')}"
puts "Different text: #{pattern.match?('aaab')}"
puts "Digits only: #{/\A[0-9]+\z/.match?("20\n")}"

Expected:

Characters: 4; UTF-8 bytes: 5
Literal match: true
Different text: false
Digits only: false
Ruby 06 - A disposable UTF-8 file

The block owns a newly created toy directory under the current practice folder. File.open blocks close their handles; mktmpdir removes its own directory when its block finishes. File.open is intentional: Kernel.open can interpret pipe-prefixed strings as process commands. No external path is accepted.

require 'tmpdir'
folder = nil
Dir.mktmpdir('atlas-ruby-', '.') do |dir|
  folder = dir
  path = File.join(dir, 'note.txt')
  File.open(path, 'w:UTF-8') { |file| file.write("café\n") }
  text = File.open(path, 'r:UTF-8') { |file| file.read }
  puts "Read: #{text.chomp}"
end
puts "Toy directory removed: #{!File.exist?(folder)}"

Expected:

Read: café
Toy directory removed: true
Ruby 07 - Parse a narrow input contract

This policy accepts decimal text 0..120 without signs, surrounding whitespace or leading zeroes. The regex bounds length before conversion. Checking nil preserves zero as a valid result. Integer alone accepts a broader syntax; to_i would silently parse some partial input. Malformed or non-ASCII-compatible string encoding is rejected before regular-expression matching.

def minutes(text)
  return nil unless text.is_a?(String) && text.valid_encoding? &&
    text.encoding.ascii_compatible? &&
    /\A(?:0|[1-9][0-9]{0,2})\z/.match?(text)
  number = Integer(text, 10)
  number <= 120 ? number : nil
end
['20', '0', '121', ' 20', '+20', '20x'].each do |text|
  value = minutes(text)
  puts(value.nil? ? 'invalid' : value)
end

Expected:

20
0
invalid
invalid
invalid
invalid
Ruby 08 - A local module

Save the companion beside the entry file. require_relative resolves relative to this source file. A module provides a namespace; self.total defines a callable module method. The module has no demonstration output when loaded.

require_relative 'Atlas minutes'
puts "Total: #{AtlasMinutes.total([20, 30])}"

Expected:

Total: 50

Companion file: Atlas minutes.rb

module AtlasMinutes
  def self.total(values)
    raise ArgumentError, 'at most ten whole minutes 0..120' unless
      values.is_a?(Array) && values.length <= 10 &&
      values.all? { |n| n.is_a?(Integer) && n.between?(0, 120) }
    values.inject(0, :+)
  end
end
Ruby 09 - JSON is data

Generate escaping with the JSON library, then validate the decoded shape separately. This tiny authored input uses create_additions: false; never substitute JSON.load or Marshal.load for untrusted data. Default duplicate-name handling is not a duplicate-rejection policy. No general hostile-input or schema claim is made.

require 'json'
encoded = JSON.generate({'topic' => 'read', 'minutes' => 20})
data = JSON.parse(encoded, create_additions: false, max_nesting: 10)
valid = data.is_a?(Hash) && data.keys.sort == ['minutes', 'topic'] &&
  data['topic'].is_a?(String) && data['minutes'].is_a?(Integer) &&
  data['minutes'].between?(0, 120)
raise ArgumentError, 'wrong contract' unless valid
puts "#{data.fetch('topic')}: #{data.fetch('minutes')}"
begin
  JSON.parse('{', create_additions: false)
rescue JSON::ParserError
  puts 'Malformed JSON rejected'
end

Expected:

read: 20
Malformed JSON rejected
Ruby exercise A - An optional average

Validate the collection, return nil for absence, and divide as floating point only for a nonempty collection. This is a bounded teaching contract, not a general statistics library.

def average(values)
  raise ArgumentError, 'at most ten whole minutes 0..120' unless
    values.is_a?(Array) && values.length <= 10 &&
    values.all? { |n| n.is_a?(Integer) && n.between?(0, 120) }
  return nil if values.empty?
  values.inject(0, :+).fdiv(values.length)
end
puts "Average: #{average([10, 20])}"
puts "Empty: #{average([]).nil?}"

Expected:

Average: 15.0
Empty: true

Practice: Implement an average of at most ten Integer minutes in 0..120. Return nil for empty input and reject invalid elements.

Ruby exercise B - Shallow copies

dup copies one container level. map(&:dup) copies each row for this specific two-level structure, but the contained string is still shared. It is not a recursive deep copy.

original = [['read', 20]]
shallow = original.dup
shallow[0][1] = 30
puts "After shallow edit: #{original[0][1]}"
separate_rows = original.map(&:dup)
separate_rows[0][1] = 40
puts "After row edit: #{original[0][1]}"
puts "Separate row: #{separate_rows[0][1]}"

Expected:

After shallow edit: 30
After row edit: 30
Separate row: 40

Practice: Predict which mutation affects the original. Then copy each row and replace a numeric cell without changing the original.

Ruby exercise C - Observable assertions

This small authored test uses raise to fail visibly. It executes three valid cases and one expected error check. A syntax check alone would not run these assertions.

def double_minutes(value)
  raise ArgumentError unless value.is_a?(Integer) && value.between?(0, 120)
  value * 2
end
checks = 0
[[0, 0], [20, 40], [120, 240]].each do |input, expected|
  raise 'wrong result' unless double_minutes(input) == expected
  checks += 1
end
rejected = false
begin
  double_minutes(-1)
rescue ArgumentError
  rejected = true
end
raise 'expected rejection' unless rejected
checks += 1
puts "Assertions: #{checks} passed"

Expected:

Assertions: 4 passed

Practice: Write checks for zero, normal input, the upper bound and a rejected negative value. Make an unexpected result exit unsuccessfully.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a bounded example
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Provide complete source and companion files, expected stdout and a small input contract. Do not claim tests ran without evidence.
Debug a reproducible failure
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Separate syntax diagnostics, loading errors and runtime exceptions; preserve a minimal reproduction. Do not claim tests ran without evidence.
Design boundary tests
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Cover zero, empty, invalid and upper-bound cases; distinguish proposed checks from executed checks. Do not claim tests ran without evidence.
Refactor observable behavior
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve outputs, exceptions, aliasing and cleanup; explain the regression evidence. Do not claim tests ran without evidence.
Document the actual contract
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. State types or scalar representations, encoding, errors, ownership, runtime limits and real evidence. Do not claim tests ran without evidence.
Explain with practice
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Use an original small example, predicted output, exercise and separate solution. Do not claim tests ran without evidence.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.