Building a Simple To-Do List Application in Ruby
1. Project Setup:
Start by creating a new directory for your project and navigate into it:
mkdir todo_app
cd todo_app
2. Create the Main Ruby File:
Inside your project directory, create a file named todo.rb
and open it in your text editor.
3. Implement the To-Do Class:
In todo.rb
, define a Todo
class to represent a single to-do item. Each to-do item will have a description and a status (complete or incomplete). Here’s a basic implementation:
class Todo
attr_accessor :description, :complete
def initialize(description)
@description = description
@complete = false
end
def to_s
"[#{complete ? 'X' : ' '}] #{description}"
end
end
This class has a constructor to initialize a to-do item and a to_s
method to provide a string representation of the to-do item.
4. Create the To-Do List Class:
Next, create a TodoList
class to manage a list of to-do items. Add methods to add, remove, and display to-do items:
class TodoList
attr_accessor :todos
def initialize
@todos = []
end
def add_todo(description)
todo = Todo.new(description)
todos << todo
end
def remove_todo(index)
todos.delete_at(index)
end
def display_todos
puts "To-Do List:"
todos.each_with_index { |todo, index| puts "#{index + 1}. #{todo}" }
end
end
5. Implement User Interface:
In the same todo.rb
file, add a simple user interface to interact with the to-do list:
todo_list = TodoList.new
loop do
puts "\n1. Add Todo"
puts "2. Remove Todo"
puts "3. Display Todos"
puts "4. Quit"
print "Choose an option: "
choice = gets.chomp.to_i
case choice
when 1
print "Enter todo description: "
description = gets.chomp
todo_list.add_todo(description)
puts "Todo added!"
when 2
print "Enter the todo number to remove: "
index = gets.chomp.to_i - 1
todo_list.remove_todo(index)
puts "Todo removed!"
when 3
todo_list.display_todos
when 4
puts "Goodbye!"
break
else
puts "Invalid option. Please choose again."
end
end
6. Run Your To-Do List App:
Save your changes and run your Ruby application:
ruby todo.rb
You should see a menu prompting you to add, remove, display, or quit. Follow the prompts to interact with your to-do list.
Conclusion:
Congratulations! You’ve just built a simple To-Do List application in Ruby. This project covers fundamental concepts such as class creation, user input handling, and basic data structures. As you continue to enhance your Ruby skills, consider exploring more advanced features, such as file I/O, error handling, and testing.
Remember that this is a starting point, and you can extend and modify the application based on your preferences and requirements. Happy coding!
Comments