Ruby TODO 待办事项命令行工具开发指南
在日常生活中,待办事项列表是帮助我们管理时间和任务的重要工具。随着技术的发展,许多待办事项应用应运而生,但有时我们可能需要一款轻量级、易于使用的工具来管理我们的任务。本文将介绍如何使用Ruby语言开发一个简单的命令行待办事项工具,该工具支持增删改查(CRUD)操作,并具备优先级和截止日期功能。
环境准备
在开始之前,请确保您的计算机上已安装Ruby。您可以通过以下命令检查Ruby版本:
ruby
ruby -v
如果未安装Ruby,请访问官方Ruby网站(https://www.ruby-lang.org/)下载并安装。
项目结构
我们的待办事项工具将包含以下文件:
- `todo.rb`:主程序文件,包含用户交互逻辑。
- `todo_list.rb`:处理待办事项列表的类。
- `todo_item.rb`:表示单个待办事项的类。
代码实现
1. 创建 `todo_item.rb`
ruby
class TodoItem
attr_accessor :title, :priority, :due_date
def initialize(title, priority, due_date)
@title = title
@priority = priority
@due_date = due_date
end
def to_s
"[{priority}] {title} (截止日期: {due_date})"
end
end
2. 创建 `todo_list.rb`
ruby
class TodoList
attr_accessor :items
def initialize
@items = []
end
def add_item(item)
@items << item
end
def remove_item(index)
@items.delete_at(index)
end
def update_item(index, title, priority, due_date)
@items[index].title = title
@items[index].priority = priority
@items[index].due_date = due_date
end
def list_items
@items.each_with_index do |item, index|
puts "{index + 1}. {item}"
end
end
end
3. 创建 `todo.rb`
ruby
require 'date'
class Todo
def initialize
@list = TodoList.new
end
def add_item
print '请输入待办事项标题: '
title = gets.chomp
print '请输入优先级(1-紧急,2-重要,3-普通): '
priority = gets.to_i
print '请输入截止日期 (格式: YYYY-MM-DD): '
due_date = Date.parse(gets.chomp)
@list.add_item(TodoItem.new(title, priority, due_date))
puts '待办事项已添加。'
end
def remove_item
print '请输入要删除的待办事项编号: '
index = gets.to_i - 1
if index.between?(0, @list.items.size - 1)
@list.remove_item(index)
puts '待办事项已删除。'
else
puts '无效的编号。'
end
end
def update_item
print '请输入要修改的待办事项编号: '
index = gets.to_i - 1
if index.between?(0, @list.items.size - 1)
print '请输入新的标题: '
title = gets.chomp
print '请输入新的优先级(1-紧急,2-重要,3-普通): '
priority = gets.to_i
print '请输入新的截止日期 (格式: YYYY-MM-DD): '
due_date = Date.parse(gets.chomp)
@list.update_item(index, title, priority, due_date)
puts '待办事项已更新。'
else
puts '无效的编号。'
end
end
def list_items
puts '待办事项列表:'
@list.list_items
end
def run
loop do
puts '请选择操作:'
puts '1. 添加待办事项'
puts '2. 删除待办事项'
puts '3. 修改待办事项'
puts '4. 显示待办事项列表'
puts '5. 退出'
choice = gets.to_i
case choice
when 1
add_item
when 2
remove_item
when 3
update_item
when 4
list_items
when 5
puts '退出程序。'
break
else
puts '无效的操作。'
end
end
end
end
主程序入口
if __FILE__ == $0
todo_app = Todo.new
todo_app.run
end
测试与运行
保存以上代码到相应的文件中,然后在命令行中运行 `ruby todo.rb`。按照提示进行操作,即可体验我们的待办事项工具。
总结
本文介绍了如何使用Ruby语言开发一个简单的命令行待办事项工具。通过实现增删改查、优先级和截止日期功能,我们能够更好地管理我们的任务。这只是一个基础版本,您可以根据自己的需求进行扩展和优化。希望本文对您有所帮助!
Comments NOTHING