Let's think this through for a second
In this first stage of the project, we'll create a Task class to represent each individual piece of data, and a TaskTracker class to manage the whole collection. The Task class holds title and done state, and we'll use attr_accessor to auto-generate the getters and setters. The TaskTracker class stores Task objects in an array, and its add_task method lets you add new tasks to it. This stage combines the intro-level concepts of oop-intro, class-object, initialize, getters-setters, and arrays. In Part 2 of the project, we'll build list/complete/delete features on top of this structure.
Let's build it for real
First, create a file called task_tracker.rb. Write the Task class with attr_accessor :title, :done, and in the initialize(title) method, set @title to the value passed in, with @done defaulting to false. Next, build the TaskTracker class — in initialize, set @tasks = [] as an empty array. In the add_task(title) method, push (<<) a Task.new(title) onto the @tasks array and puts a confirmation message. Also add a tasks reader method so the @tasks array can be read from outside the class. Finally, build a tracker object with TaskTracker.new, add a couple of tasks with add_task, and check it with p tracker.tasks.
Code Example
class Task
attr_accessor :title, :done
def initialize(title)
@title = title
@done = false
end
end
class TaskTracker
def initialize
@tasks = []
end
def add_task(title)
@tasks << Task.new(title)
puts "Added: #{title}"
end
def tasks
@tasks
end
end
tracker = TaskTracker.new
tracker.add_task("Buy milk")
tracker.add_task("Learn Ruby")
p tracker.tasksThe terminal should print two messages, "Added: Buy milk" and "Added: Learn Ruby", followed by an array containing two Task objects.5-Minute Challenge
Besides the task title, add a priority (:low, :medium, :high) attribute to the Task class and update initialize and attr_accessor accordingly — try it in 5 minutes.
One Quick Warning
Be careful to use attr_accessor, attr_reader, and attr_writer appropriately — if you want to update the done attribute from outside the class, you'll need attr_accessor (or at least attr_writer).