Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'colorize' # I can haz yellow?!
- #def writeFile(list)
- #File.truncate(0)
- #File.open("todo.txt", "r+") do |file, list, index|
- #file.puts list[index]
- #end
- #end
- # Show to-do list
- def showList(list)
- if list.length == 0
- puts "There's nothing on your to-do list."
- else
- list.each_with_index do |item, index|
- # + 1 so user doesn't see 0
- puts "#{index+1}. #{item}"
- end
- end
- end
- # Add to list
- def addItem!(list, new)
- File.open($file, "a") do |file|
- list.push(new)
- file.puts list[(list.length - 1)]
- puts "\"#{list[(list.length - 1)]}\" added."
- end
- end
- # Remove from list
- def removeItem!(list)
- if list.length == 0
- puts "There's nothing on your to-do list."
- else
- puts "Number to remove:"
- index = gets.chomp.to_i
- if index < 1 && index >= (list.length + 1)
- # remember that the index is - 1 what the user sees on the screen
- puts "Enter a valid number."
- removeItem!(list)
- else
- list.delete_at(index - 1)
- # We have to re-write the modified list now,
- # starting at the very begining of the file (indicated by '+'
- # as opposed to 'a'"
- File.truncate($file, 0) # WARNING: Truncate isn't cross platform. It won't work on windows or mac.
- #File.open("todo.txt", "r+") do |file, list, index|
- list.each_with_index do |list, index|
- $file.puts list[index]
- # Ruby is error:
- # `block in removeItem!': undefined local variable or method `file' for main:Object (NameError)
- end
- #end
- end
- end
- end
- # Edit list item
- def editItem!(list)
- if list.length == 0
- puts "There's nothing on your to-do list."
- else
- puts "Number to edit:"
- index = gets.chomp.to_i
- if index < 1 && index >= (list.length + 1)
- puts "Enter a valid number."
- editItem!(list)
- else
- edited_item = gets.chomp
- list[index-1] = edited_item
- File.open($file, "r+") do |file|
- # re-write the modified list from the begining!
- file.puts list
- end
- end
- end
- end
- # User interface
- def menu(list)
- puts "\n(S)how list \t (A)dd item \t (R)emove item \t (E)dit item \t (Q)uit".green
- option = gets.chomp.downcase
- case option
- when 's'
- showList(list)
- when 'a'
- puts "What do you want to add?"
- text = gets.chomp
- addItem!(list, text)
- when 'r'
- removeItem!(list)
- when 'e'
- editItem!(list)
- when 'q'
- exit
- else
- menu(list)
- end
- menu(list)
- end
- # Let's go!
- $file = "todo.txt"
- File.open($file, "a+")
- todo_list = IO.readlines($file)
- menu(todo_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement