Let's think this through for a second
Taking the Task and TaskTracker class structure from Part 1 as our base, this stage adds the app's core features. We'll use the each_with_index iterator to display the task list along with index numbers, and a ternary operator (? :) to show done status as [x] or [ ]. The complete_task and delete_task methods use if-else logic to check whether the task exists and handle the error case. By the end of this stage, the app won't just create tasks — it'll be a tool that tracks them.
Let's build it for real
Add a list_tasks method to the TaskTracker class — loop with @tasks.each_with_index do |task, i|, use a ternary to set status = task.done ? "[x]" : "[ ]", and puts "#{i + 1}. #{status} #{task.title}". Next, write the complete_task(index) method — grab the task at @tasks[index - 1], and if it exists set task.done = true, otherwise show "Task not found". For delete_task(index), use @tasks.delete_at(index - 1) to remove the task from the array, and show a different message depending on the result. Finally, wrap it all in a loop do...end block that reads user input with gets.chomp and uses case/when to route commands like "list", "add", "done", "delete", and "exit" to their respective methods.
Code Example
class TaskTracker
# Part 1 ရဲ့ initialize, add_task, tasks ကို ဆက်သုံးပါမယ်
def list_tasks
@tasks.each_with_index do |task, i|
status = task.done ? "[x]" : "[ ]"
puts "#{i + 1}. #{status} #{task.title}"
end
end
def complete_task(index)
task = @tasks[index - 1]
if task
task.done = true
puts "Completed: #{task.title}"
else
puts "Task not found"
end
end
def delete_task(index)
task = @tasks.delete_at(index - 1)
task ? (puts "Deleted: #{task.title}") : (puts "Task not found")
end
end
tracker = TaskTracker.new
loop do
print "> "
input = gets.chomp
case input
when "list"
tracker.list_tasks
when /^add /
tracker.add_task(input.sub("add ", ""))
when /^done /
tracker.complete_task(input.sub("done ", "").to_i)
when "exit"
break
end
endIn the terminal, the list command shows the task list along with its status, and the done/delete commands let you change a task's state.5-Minute Challenge
Add the delete command to your case/when block too, so input like "delete 2" can delete a task — try it in 5 minutes.
One Quick Warning
Don't forget to convert the index string the user typed with .to_i — otherwise you can't use it as an array index.