Thuta Learning
Ruby
ProjectsProgrammingBeginner

Task Tracker Project - Part 2

RubyLesson 3140 min

What you'll walk away with

  • Look up, complete and remove tasks by id, and raise a custom TaskNotFound error when an id does not exist
  • Explain why a position in a list is a poor identifier (the negative-index trap) and why ids stay stable
  • Parse text commands with split and case/when, and convert a typed number with Integer(text, 10, exception: false)
  • Keep the command layer free of direct I/O by returning Strings, so a script or a real terminal can drive it
  • Rescue specific errors at one boundary and turn them into friendly messages

Explain it simply

Explain it simply

Part 1 gave you a tracker that can only add tasks. Part 2 makes it usable: you will find a task, mark it done, delete it, and drive all of that with text commands like add, list, done 2 and delete 1.

The new layer is a thin translator. It takes one line of text, decides which tracker method it means, and returns a reply as a string. All the real rules still live in the classes from Part 1, so the translator stays short, and when someone types nonsense it answers with a polite message instead of crashing.

Problem → Why → Solution

The problem: commands that pick by position

The obvious way to let a user pick a task is by its position in the list: "done 1" completes the first task. It feels natural, and the Ruby for it is one line: tasks[number - 1]. The trouble starts with the numbers a user might type. Position 0 becomes index -1, and in Ruby a negative index counts from the end, so tasks[-1] quietly returns the last task. "done 0" completes the wrong task and reports success.

Positions also move. Delete task 1 and every other task shifts up, so "done 3" now means a different task than it did a minute ago. A command log or a saved file full of positions would be meaningless.

positions.rb
tasks = ["Buy milk", "Learn Ruby", "Write tests"]

def pick(tasks, number)
  tasks[number - 1]
end

p pick(tasks, 2)   # "Learn Ruby"
p pick(tasks, 0)   # "Write tests" - index -1 is the LAST element, no error
p pick(tasks, 7)   # nil - and nil.title would crash later
tasks.delete_at(0)
p pick(tasks, 2)   # "Write tests" - the same number now means another task

Why doesn't Ruby complain?

Ruby's array indexing never raises for a wrong position: negative numbers wrap around, and numbers past the end give nil. That is convenient in loops and dangerous for user input. A stable id plus a lookup that raises when nothing matches turns every wrong number into a visible error.

Core concept: lookups that fail loudly, commands that return strings

Part 2 adds two things on top of Part 1: tracker methods that act on one task, and a command layer that calls them. Both follow the same idea: make success obvious and failure impossible to miss.

1. Look up by id with fetch, which raises

TaskTracker#fetch(id) finds the task whose id matches, or raises TaskNotFound. The name is borrowed from Hash#fetch and Array#fetch, which also raise for a missing key. A caller can no longer receive nil by accident and crash two lines later with a NoMethodError.

2. Define your own error class

class TaskNotFound < StandardError gives this failure a name. Callers rescue exactly that class without also catching typos or bugs, and the message ("no task with id 99") is built once, inside the class, so every part of the program reports it the same way.

3. Change state through intention-revealing methods

complete(id) fetches the task and calls Task#complete!, which sets @done to true and returns self. remove(id) fetches first and deletes second, so a missing id raises before anything changes. Both return the task, which lets the command layer print what happened.

4. Parse numbers strictly

A user's number arrives as text. "abc".to_i is 0 and "12abc".to_i is 12, and both are silently wrong. Integer(text, 10, exception: false) returns nil unless the whole text is a valid base-10 integer, and the explicit 10 stops "010" from being read as octal 8.

5. Return strings from the command layer

Cli#execute(line) splits the line into a command word and an optional argument, picks a tracker method with case/when, and returns a reply. It never calls puts itself. The caller decides where the reply goes: a terminal, a test, or a web page.

6. Rescue once, at the boundary

execute ends with a single rescue for TaskNotFound and ArgumentError and converts them into "Error: ..." replies. The model raises, the boundary translates, and the inner methods stay free of begin/rescue clutter.

Typed lineReply (and why)
done 2Completed #2 ... (task 2 exists)
done 99Error: no task with id 99 (TaskNotFound)
done twoError: expected a task id (Integer() returned nil)
add (no title)Error: title can't be blank (Task.new raised)
bogusUnknown command plus the help text
Mental model: a translator at the door
  1. Read one line of text
  2. Split into command + argument
  3. Call one tracker method
  4. Return a reply String
  5. Rescue errors into messages

Text comes in, a string goes out. Everything between those two points is ordinary Ruby that a test can call without a terminal.

General pattern

ruby
def fetch(id) = @items.find { |item| item.id == id } || raise(NotFound, id)

def execute(line)
  command, arg = line.strip.split(/\s+/, 2)
  case command
  when "show" then show(arg)
  else "Unknown command #{command.inspect}"
  end
rescue NotFound => e
  "Error: #{e.message}"
end

fetch raises when nothing matches. execute splits the command, picks a method, and a single rescue at the end turns failures into reply strings.

Part 2 code: look up, complete, delete and a command layer

The file contains Part 1's Task and TaskTracker plus the additions marked "New in Part 2" in the comments: Task#complete!, TaskTracker's fetch, complete, remove and pending, the new TaskNotFound error and the Cli class. A scripted session is fed to the Cli one line at a time, and each reply is printed under the command that caused it.

task_tracker.rb
# New in Part 2: a named error, so callers can rescue exactly this situation.
class TaskNotFound < StandardError
  def initialize(id)
    super("no task with id #{id}")
  end
end

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

  # New in Part 2: the only way a task changes after it was created.
  def complete!
    @done = true
    self
  end

  def to_h
    { "id" => id, "title" => title, "priority" => priority.to_s, "done" => done? }
  end

  def to_s
    "##{id} [#{done? ? "x" : " "}] #{title} (#{priority})"
  end
end

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?

  # New in Part 2: look up, complete and remove by id. fetch raises when nothing matches.
  def fetch(id)
    @tasks.find { |task| task.id == id } || raise(TaskNotFound, id)
  end

  def complete(id) = fetch(id).complete!

  def remove(id)
    task = fetch(id)
    @tasks.delete(task)
    task
  end

  def pending = reject(&:done?)
end

# New in Part 2: turns one line of text into a tracker call and returns a String reply.
class Cli
  HELP = "commands: add <title> [!low|!medium|!high], list, done <id>, delete <id>"

  def initialize(tracker)
    @tracker = tracker
  end

  def execute(line)
    command, arg = line.strip.split(/\s+/, 2)
    case command
    when "add"    then add(arg)
    when "list"   then list
    when "done"   then "Completed #{@tracker.complete(parse_id(arg))}"
    when "delete" then "Deleted #{@tracker.remove(parse_id(arg))}"
    when nil      then HELP
    else "Unknown command #{command.inspect}. #{HELP}"
    end
  rescue TaskNotFound, ArgumentError => e
    "Error: #{e.message}"
  end

  private

  def add(arg)
    title, flag = arg.to_s.match(/\A(.*?)(?:\s+!(\w+))?\z/).captures
    priority = flag ? flag.to_sym : :medium
    "Added #{@tracker.add(title, priority: priority)}"
  end

  def list
    return "No tasks yet." if @tracker.empty?

    lines = @tracker.map(&:to_s)
    lines << "#{@tracker.pending.size} of #{@tracker.size} pending"
    lines.join("\n")
  end

  def parse_id(text)
    id = Integer(text.to_s, 10, exception: false)
    id || raise(ArgumentError, "expected a task id, got #{text.inspect}")
  end
end

script = <<~SESSION
  add Buy milk !high
  add Learn Ruby
  add Write tests !low
  list
  done 2
  done 99
  done two
  delete 1
  add
  add Plan trip !urgent
  list
  bogus
SESSION

cli = Cli.new(TaskTracker.new)
script.each_line do |line|
  puts "> #{line.strip}"
  puts cli.execute(line)
end

Code breakdown

  1. fetch raises instead of returning nil@tasks.find { |task| task.id == id } || raise(TaskNotFound, id)

    find returns nil when nothing matches, and the right side of || then raises. That is why "done 99" produces "Error: no task with id 99" and no task is touched.

  2. An error that builds its own messagesuper("no task with id #{id}")

    The class builds the message itself. raise(TaskNotFound, id) passes the id to initialize, so every raise site uses the same wording.

  3. Fetch first, delete secondtask = fetch(id)

    The first line of remove is fetch. A missing id raises right there and @tasks.delete(task) is never reached. The task is returned after deletion, which is how "Deleted #1 ..." can be printed.

  4. Split with a limitcommand, arg = line.strip.split(/\s+/, 2)

    The second argument, 2, caps the result at two parts, so "add Buy fresh milk" becomes ["add", "Buy fresh milk"] and the spaces inside the title survive. For a bare "list" the arg is nil.

  5. Strict number parsingid = Integer(text.to_s, 10, exception: false)

    text.to_s lets a missing argument through as well. When the result is nil, the next line raises ArgumentError and the message reads expected a task id, got "two".

  6. A priority flag at the endtitle, flag = arg.to_s.match(/\A(.*?)(?:\s+!(\w+))?\z/).captures

    (.*?) takes as little title as it can, and the optional group (?:\s+!(\w+))? captures a trailing !high. \A and \z anchor the match to the whole string. A wrong priority such as !urgent is rejected later by Task.new.

  7. One boundary rescuerescue TaskNotFound, ArgumentError => e

    Both errors become "Error: ..." replies. Note that ArgumentError is broad and would also catch a wrong-argument-count bug of your own, which is one reason this rescue lives in a method as short as execute.

You should see
> add Buy milk !high
Added #1 [ ] Buy milk (high)
> add Learn Ruby
Added #2 [ ] Learn Ruby (medium)
> add Write tests !low
Added #3 [ ] Write tests (low)
> list
#1 [ ] Buy milk (high)
#2 [ ] Learn Ruby (medium)
#3 [ ] Write tests (low)
3 of 3 pending
> done 2
Completed #2 [x] Learn Ruby (medium)
> done 99
Error: no task with id 99
> done two
Error: expected a task id, got "two"
> delete 1
Deleted #1 [ ] Buy milk (high)
> add
Error: title can't be blank
> add Plan trip !urgent
Error: priority must be one of [:low, :medium, :high], got :urgent
> list
#2 [x] Learn Ruby (medium)
#3 [ ] Write tests (low)
1 of 2 pending
> bogus
Unknown command "bogus". commands: add <title> [!low|!medium|!high], list, done <id>, delete <id>
Life of one command line
  1. Receive the text "done 2"
  2. Split into command and argument
  3. Parse the id with Integer(text, 10)
  4. Call tracker.complete(id)
  5. Return "Completed #2 ..."

The id exists

A Completed reply is returned

Missing id or not a number

An Error reply is returned and nothing changes

Driving it from a real terminal

Because Cli#execute only returns a string, running it on a terminal takes just a small loop. The key is $stdin.gets. When input ends (Ctrl-D, or the end of a piped file) gets returns nil, so while (line = $stdin.gets) stops cleanly. Writing gets.chomp instead crashes at that moment with "undefined method 'chomp' for nil (NoMethodError)" on Ruby 4.0.9.

bin/tracker
# Needs Task, TaskTracker and Cli from the example above.
cli = Cli.new(TaskTracker.new)
puts Cli::HELP

while (line = $stdin.gets)
  break if line.strip == "exit"

  puts cli.execute(line)
end

In tests you can substitute a StringIO for $stdin, because StringIO answers gets and each_line the same way. The snippet below shows what happens when the input runs out. Tests written against scripted input never need someone to sit and type.

scripted_input.rb
require "stringio"

input = StringIO.new("add Buy milk\nlist\n")

while (line = input.gets)
  puts "got: #{line.strip}"
end

puts "at the end, gets returns #{input.gets.inspect}"

In real projects

In real projects

Command parsers like this one sit at the edge of real tools: a chat bot reading "/remind 3", a git sub-command, a REPL, the admin console of a web app. The pattern is always the same: split the line, dispatch on the first word, call a method on a domain object, and turn failures into messages. Because execute returns a string instead of printing, one Cli class can answer a terminal today and a Slack message or a test assertion tomorrow.

Custom error classes matter more as programs grow. A web app rescues a NotFound class and renders a 404 page, rescues a validation class and renders a form with messages, and lets everything else fall through to a monitoring tool. If TaskNotFound were a bare RuntimeError carrying a string, that routing would be impossible. Using ids instead of positions is the same lesson: a web URL such as /tasks/42 stays valid when other rows are deleted for exactly this reason.

Common mistakes

Common mistakes

Letting to_i guess the id

"two".to_i is 0, which with position math becomes tasks[-1] and completes the last task. Even with ids, "12abc".to_i is 12 and completes task 12 although the user typed nonsense. Use Integer(text, 10, exception: false) and treat nil as an error.

Rescuing StandardError everywhere

A bare rescue => e at the top of execute would also swallow a NoMethodError caused by your own typo and turn it into a polite "Error: undefined method" reply, hiding a bug. Rescue the specific classes you expect: TaskNotFound and ArgumentError.

Trusting delete_at to report a missing task

@tasks.delete_at(99) returns nil without any error, and @tasks.delete(task) also returns nil when nothing matches. Feed that nil into "Deleted #{task.title}" and the NoMethodError appears one line later. Find the task with fetch first, then delete it.

Printing inside the model

If complete calls puts "Completed" itself, a test cannot call it quietly and another interface cannot reuse it. Return the task and leave the formatting to the caller.

Best practices

Best practices

  • Name errors after the situation (TaskNotFound), not the mechanism
  • Put the error message inside the error class so every raise site matches
  • Keep one rescue at the boundary and let the inner methods stay clean
  • Parse text once, at the edge, into an Integer, Symbol or Date before calling the model

Mini challenge

Complete several tasks at once

Write parse_ids(text) so a command like done 1 3 5-7 can name several tasks. It returns two Arrays: the ids to act on, and the tokens that could not be understood.

  • Split on whitespace and accept plain numbers and inclusive ranges such as 5-7
  • Keep ids in the order given and drop duplicates
  • Report every bad token instead of stopping at the first (letters, 0 or negative numbers, a reversed range like 7-5, a range wider than 1000 ids)
  • Blank or nil text returns two empty arrays
parse_ids.rb
def parse_ids(text)
  ids = []
  rejected = []

  # TODO: split the text into tokens (nil must behave like "")
  # TODO: a token is either "7" or "5-7" - anything else goes into rejected
  # TODO: a range expands to every id from first to last; first > last is rejected
  # TODO: keep ids in order without duplicates

  [ids, rejected]
end

Expected: One line per input, showing ids=[...] and rejected=[...]. "1 3 5-7" gives [1, 3, 5, 6, 7], "4 x 0 7-5 -1" gives ids [4] with "x", "0", "7-5" and "-1" rejected, and both the blank string and nil give two empty arrays.

Show hint

Test each token against a regular expression such as /\A(\d+)(?:-(\d+))?\z/. When the second capture is missing it is a single number, so use last = first. (first..last).to_a expands a range, and uniq removes duplicates at the end.

Show solution
parse_ids.rb
# Turns "1 3 5-7" into the ids to act on, and collects every token it cannot use.
def parse_ids(text)
  ids = []
  rejected = []

  text.to_s.split.each do |token|
    match = token.match(/\A(\d+)(?:-(\d+))?\z/)
    first = match && match[1].to_i
    last = match && (match[2] || match[1]).to_i

    if first.nil? || first < 1 || last < first || last - first >= 1000
      rejected << token
    else
      ids.concat((first..last).to_a)
    end
  end

  [ids.uniq, rejected]
end

["1 3 5-7", "2 2 1", "4 x 0 7-5 -1", "  9   10-11  ", "1-5000", "", nil].each do |text|
  ids, rejected = parse_ids(text)
  puts "#{text.inspect} -> ids=#{ids.inspect} rejected=#{rejected.inspect}"
end

Quick quiz 1 / 3

A user types "done 0". The tracker looks the task up with tasks[number - 1]. What happens?

Quick quiz 2 / 3

What does Integer("12abc", 10, exception: false) return?

Quick quiz 3 / 3

Why does TaskTracker#remove call fetch(id) before deleting anything?

What to remember

  • Picking by position breaks on negative indexes and shifting numbers, so use a stable id
  • fetch raises your own error (TaskNotFound) instead of quietly returning nil
  • Parse the user's number strictly with Integer(text, 10, exception: false)
  • Cli#execute returns a string and rescues only the errors it expects, at the boundary
  • The nil from $stdin.gets and StringIO let one command layer serve a terminal and scripted tests

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Task Tracker Project - Part 2 | Thuta Learning