Explain it simply
Explain it simply
This is the first of three lessons that build one program, a Task Tracker you drive with short text commands. Part 1 contains no commands at all. It answers a smaller question first: what is a task, and who is allowed to create one?
Think of a reception desk that hands out numbered tickets. The clerk refuses to write a ticket for a blank name, and the numbers only ever go up. Here the Task class is the ticket and the TaskTracker class is the clerk. When both are strict, the commands in Part 2 and the file storage in Part 3 can trust the data they receive.
Problem → Why → Solution
The problem: a task list with no rules
A quick first draft usually stores each task as a Hash in an array. It takes five minutes to write and it accepts anything. A blank title, a priority typo such as :hgh and a done flag set to the string "yes" all go in without a complaint, and the program only misbehaves much later, when a report sorts tasks in the wrong order or a checkbox is ticked on every row.
The draft also picks ids with tasks.size + 1, which is fine until the first delete. After that, two different tasks end up with the same id, and every command that says "complete task 2" has to guess which one you meant.
tasks = []
tasks << { id: tasks.size + 1, title: "Buy milk", priority: :high, done: false }
tasks << { id: tasks.size + 1, title: "", priority: :hgh, done: "yes" } # accepted
tasks.delete_at(0)
tasks << { id: tasks.size + 1, title: "Write tests", priority: :low, done: false }
puts tasks.map { |t| t[:id] }.inspect # [2, 2] - two tasks, one idWhy did nothing stop it?
A Hash has no rules of its own, and a plain attr_accessor happily accepts any value. To enforce a rule you need one place that every task passes through on its way into the program. A constructor is that place: if initialize raises on bad input, an invalid Task simply cannot exist, and the rest of the program never has to check again.
Core concept: make invalid tasks impossible
Before you write a single command, write down what a valid task is. For this tracker the rules are short: the id is a positive integer, the title is not blank once the spaces are trimmed, the priority is one of :low, :medium or :high, and done is exactly true or false. Everything in Part 1 exists to make those four rules impossible to break.
1. Write the rules as code inside initialize
A constructor is the single doorway through which every Task enters the program. Check each rule there and raise ArgumentError with a message that shows the bad value. Using inspect makes nil, an empty string and :hgh look different. Normalise at the same moment: strip the title so that " Buy milk " and "Buy milk" are the same task.
2. Give read access, not write access
attr_reader creates getters only. There is no title= method, so nobody can replace a valid title with a blank one after the fact. Changes go through named methods that keep the rules, such as complete! in Part 2. attr_accessor would have created a setter for every field and quietly deleted every rule you just wrote.
3. Let the tracker own the ids
TaskTracker keeps @next_id. It creates the Task first and increments the counter only after the constructor has succeeded, so a rejected task never uses up an id. Because the counter only goes up, deleting a task later cannot make two tasks share an id, which was the problem the draft had with size + 1.
4. Expose iteration, not the array
The tracker defines each and includes Enumerable. That one decision hands callers map, select, count, sort_by, min_by, first and tally for free while @tasks stays private. Nobody can push a raw Hash into your list, because nobody ever receives the list itself.
5. Add a plain-data view
to_h returns the task as a Hash with string keys: id, title, priority (as a String) and done. A Hash of strings, numbers and booleans is exactly what JSON can store, so in Part 3 saving a task is a single call.
| Representation | What you get | What it costs |
|---|---|---|
| Hash | No setup, prints easily | No rules, a mistyped key fails silently |
| Struct | Accessors, ==, to_a in one line | A setter on every field, validation is up to you |
| A class with validation | Rules enforced in one place, control over the API | More lines to write |
- Task: validate in initialize
- Tracker: assign the next id
- Create the Task first
- Only then store it and bump the id
If creation fails, nothing was stored and no id was used, so the list stays exactly as it was.
General pattern
class Thing
attr_reader :name
def initialize(name:)
raise ArgumentError, "bad name" if name.to_s.strip.empty?
@name = name.strip
end
end
class Collection
include Enumerable
def initialize; @items = []; end
def each(&block) = @items.each(&block)
endThe first class checks its input in the constructor and offers readers only. The second keeps its list private and borrows Enumerable's methods through a single each.
Part 1 code: the model and the first tracker
The file below is complete: run it with ruby task_tracker.rb. It adds five tasks on purpose, two of them invalid, so you can watch the rescue path and see that the ids still run 1, 2, 3. Part 2 keeps every line of Task and TaskTracker and adds to them, so read the names carefully now.
Output depends on the Ruby version
Output in this tutorial comes from Ruby 4.0.9. Ruby 3.4 and later print a Hash as {high: 1} and {"id" => 1}; Ruby 3.3 and earlier print {:high=>1} and {"id"=>1}. The behaviour is the same, only the printed text differs.
# A task has an id, a title, a priority and a done flag, and it refuses bad data.
class Task
PRIORITIES = %i[low medium high].freeze
attr_reader :id, :title, :priority
def initialize(id:, title:, priority: :medium, done: false)
unless id.is_a?(Integer) && id.positive?
raise ArgumentError, "id must be a positive integer"
end
clean = title.to_s.strip
raise ArgumentError, "title can't be blank" if clean.empty?
unless PRIORITIES.include?(priority)
allowed = PRIORITIES.inspect
raise ArgumentError, "priority must be one of #{allowed}, got #{priority.inspect}"
end
raise ArgumentError, "done must be true or false" unless [true, false].include?(done)
@id = id
@title = clean
@priority = priority
@done = done
end
def done? = @done
def to_h
{ "id" => id, "title" => title, "priority" => priority.to_s, "done" => done? }
end
def to_s
"##{id} [#{done? ? "x" : " "}] #{title} (#{priority})"
end
end
# The tracker owns the list and hands out ids.
class TaskTracker
include Enumerable
def initialize
@tasks = []
@next_id = 1
end
def add(title, priority: :medium)
task = Task.new(id: @next_id, title: title, priority: priority)
@tasks << task
@next_id += 1
task
end
def each(&block)
return enum_for(:each) unless block
@tasks.each(&block)
self
end
def size = @tasks.size
def empty? = @tasks.empty?
end
tracker = TaskTracker.new
[
["Buy milk", :high],
["Learn Ruby", :medium],
[" ", :low],
["Write tests", :low],
["Plan trip", :urgent],
].each do |title, priority|
task = tracker.add(title, priority: priority)
puts "Added #{task}"
rescue ArgumentError => e
puts "Rejected: #{e.message}"
end
puts "Tasks: #{tracker.size}"
puts "Titles: #{tracker.map(&:title).inspect}"
puts "By priority: #{tracker.map(&:priority).tally}"
puts "Done so far: #{tracker.count(&:done?)}"
p tracker.first.to_hCode breakdown
- Validate, then normalise
raise ArgumentError, "title can't be blank" if clean.empty?clean is the stripped title, so " " becomes "" and is rejected. Because of title.to_s, a nil title gets the same friendly message instead of a NoMethodError.
- A frozen list of allowed values
PRIORITIES = %i[low medium high].freeze%i[...] is shorthand for an array of symbols, and freeze stops anyone from appending to it later. The error message uses PRIORITIES.inspect, which is why it prints [:low, :medium, :high].
- Readers only
attr_reader :id, :title, :priorityThere are no setters. done is read through the done? method, following the Ruby habit that a name ending in ? answers true or false. Part 2 adds complete! for changing it.
- Create first, count second
task = Task.new(id: @next_id, title: title, priority: priority)If Task.new raises, the @tasks << task and @next_id += 1 lines below never run. That is why the ids stay 1, 2, 3 even though " " and :urgent were rejected in between.
- Enumerable from one method
def each(&block)Without a block it returns enum_for(:each), so calls like tracker.each.next work. This single each is why map(&:title), tally, count(&:done?) and first all work.
- Rescue inside a block
rescue ArgumentError => eSince Ruby 2.5 a do...end block can carry its own rescue without begin. When one row fails, the message is printed and the loop moves on to the next row.
Added #1 [ ] Buy milk (high)
Added #2 [ ] Learn Ruby (medium)
Rejected: title can't be blank
Added #3 [ ] Write tests (low)
Rejected: priority must be one of [:low, :medium, :high], got :urgent
Tasks: 3
Titles: ["Buy milk", "Learn Ruby", "Write tests"]
By priority: {high: 1, medium: 1, low: 1}
Done so far: 0
{"id" => 1, "title" => "Buy milk", "priority" => "high", "done" => false}- tracker.add(title, priority:) is called
- Task.new checks id, title, priority and done
- The task is pushed onto the list
- The counter moves to the next id
All four rules hold
add returns the new Task
A rule fails
ArgumentError raised, list and counter unchanged
Where Parts 2 and 3 are heading
Part 1 gives you the two classes at the bottom of a small stack. Each later lesson adds one layer on top and leaves the layers below untouched. That is why the names Task and TaskTracker, and the keys of to_h, matter: they are the contract the other layers depend on.
The three-part stack
--------------------
Part 3 TaskStore reads and writes tasks.json
|
Part 2 Cli turns "done 2" into tracker.complete(2)
|
Part 1 TaskTracker owns the list and the next id
|
Part 1 Task validates one id, title, priority, doneKeep the direction of the arrows in mind: the Cli knows about the tracker, the store knows about the tracker, but the tracker knows nothing about either of them. That one-way dependency is what lets you replace the interface or the storage later.
Reading what Ruby prints
p, puts and string interpolation do not print an object the same way. puts and "#{...}" call to_s, which is why Task defines a readable one-line version. p calls inspect, which lists every instance variable and a memory address that changes on every run. Do not copy inspect output into tests or expected-output blocks.
class Pet
def initialize(name)
@name = name
end
def to_s
"Pet #{@name}"
end
end
pet = Pet.new("Mimi")
puts pet # puts calls to_s
puts "Hello, #{pet}" # so does interpolation
puts pet.inspect.sub(/0x\h+/, "0x...") # p would print this, with a real address
puts({ "id" => 1, high: 2 }.inspect)The last line shows how Ruby 4.0.9 prints a Hash: a symbol key appears as high: 2 and a string key as "id" => 1. To check whether two hashes are equal, compare them directly with == instead of comparing their printed text.
In real projects
In real projects
Every real application has this layer, even when it hides behind a framework. A Rails model such as Task validates presence and inclusion before a row is written, and the database owns the id through a sequence, which is the same job @next_id does here. Teams that skip the model layer end up scattering checks across controllers and views, and the checks disagree with each other.
Keeping the model free of puts and gets pays off immediately. Because Task and TaskTracker never print or read input, the same classes will serve a command-line tool in Part 2, a JSON file in Part 3, and later a web page or a test suite without a single change. Ruby also offers Data.define (Ruby 3.2 and later) for records that never change after creation; a task has to be completed later, so a normal class fits better here.
Common mistakes
Common mistakes
Using the id before the Task exists
Writing @next_id += 1 on the line before Task.new looks harmless. The first time validation fails, the counter has moved on and the list has a hole: ids 1, 2, 4. Nothing crashes, but users notice "missing" tasks and tests that count ids start to fail. Create the task first, then increment.
Giving every field a setter
attr_accessor :title, :priority makes task.priority = :hgh legal, so the checks in initialize protect only the first moment of the object's life. Use attr_reader and add a named method (complete!, rename) for every change you really want to allow.
Returning the internal array
def tasks = @tasks hands out the real list. The caller can call tracker.tasks.clear or push a raw Hash into it, and the tracker never finds out. Expose each (with Enumerable), or return a copy with @tasks.dup, and never the array itself.
Calling strip on a possible nil
title.strip raises NoMethodError when title is nil, a confusing message for a caller who only forgot an argument. title.to_s.strip turns nil into an empty string and lets the friendly "title can't be blank" error appear.
Best practices
Best practices
A few habits keep a model class honest as the project grows.
- Raise ArgumentError with a message that includes the bad value, written with inspect
- Normalise input (strip, downcase) in one place, at the constructor
- End predicates with ? and methods that change state with !
- Keep puts out of model classes so tests can call them silently
Mini challenge
Pick the next task to work on
Add a next_up method to the tracker. It returns the pending task that should be worked on next: the highest priority first, and when two tasks share a priority, the one with the lower id. If nothing is pending, it returns nil instead of raising.
- Skip tasks whose done flag is true
- Rank :high above :medium above :low using a Hash lookup rather than a chain of if statements
- Break priority ties with the lowest id so the answer never depends on insertion order
- Return nil for an empty tracker and for a tracker where every task is done
# Reuse Task and TaskTracker from the lesson, then add this method.
class TaskTracker
RANK = {} # TODO: map :low, :medium and :high to numbers (bigger = more urgent)
def next_up
# TODO: ignore finished tasks
# TODO: choose the best one: highest RANK first, then the lowest id
# TODO: an empty result must give nil, not an exception
end
endExpected: Four calls print: the high-priority task with the lowest id, a medium task once the high ones are done, nil when everything is done, and nil for an empty tracker.
Show hint
min_by accepts an Array as its sort key, and Ruby compares Arrays element by element, so [-rank, id] means "bigger rank first, then smaller id". min_by on an empty collection returns nil by itself.
Show solution
# A trimmed stand-in for the lesson's Task keeps this file short.
Task = Struct.new(:id, :title, :priority, :done, keyword_init: true)
class TaskTracker
include Enumerable
RANK = { low: 0, medium: 1, high: 2 }.freeze
def initialize(tasks)
@tasks = tasks
end
def each(&block)
@tasks.each(&block)
end
# Highest priority first; the lowest id wins a tie; nil when nothing is pending.
def next_up
reject(&:done).min_by { |task| [-RANK.fetch(task.priority), task.id] }
end
end
tasks = [
Task.new(id: 1, title: "Buy milk", priority: :medium, done: false),
Task.new(id: 2, title: "Fix login bug", priority: :high, done: false),
Task.new(id: 3, title: "Pay rent", priority: :high, done: false),
Task.new(id: 4, title: "Water plants", priority: :low, done: true),
]
tracker = TaskTracker.new(tasks)
puts "Ties on :high go to the lowest id:"
p tracker.next_up&.title
tasks[1].done = true
tasks[2].done = true
puts "After finishing both :high tasks:"
p tracker.next_up&.title
tasks[0].done = true
puts "Everything done:"
p tracker.next_up&.title
puts "Empty tracker:"
p TaskTracker.new([]).next_up&.titleQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Start by writing down what a valid task is, then enforce it in the constructor
- attr_reader plus named methods protect the rules that attr_accessor would bypass
- The tracker owns the ids and moves the counter only after a Task was created successfully
- each plus Enumerable gives collection methods while keeping @tasks hidden
- The string-key Hash from to_h is the shape Part 3 will save as JSON
Official Ruby Documentation — Ruby Documentation