-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.rb
More file actions
92 lines (82 loc) · 1.73 KB
/
list.rb
File metadata and controls
92 lines (82 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
class List
def initialize(name)
@name = name
@file_path = "./lists/#{name}.txt"
@list = []
end
def view
puts "View #{@name}'s to-do list:"
if file_exist?
unless file_empty?
File.open(@file_path, 'r') do |file|
file.each_line do |line|
puts "#{file.lineno}. #{line}"
end
end
else
puts "Your file is empty."
end
else
create
end # if exist
end
def add
# check whether the file exists and read into an array, otherwise create a new file
system 'clear'
puts "Add a task to the list:"
puts
print "> "
task = gets.strip
@list = file_to_array(@file_path)
# add the task to the array
@list << task
# write the contents of the array back into the file
array_to_file(@list)
puts "Succes!"
end
def remove
system 'clear'
puts "Remove a task from the list:"
@list = file_to_array(@file_path)
view
puts "Enter the task number:"
print "> "
task_no = gets.to_i - 1
@list.delete_at task_no
puts "Success!"
array_to_file(@list)
end
private
def file_empty?
File.zero?(@file_path)
end
def file_exist?
File.exist?(@file_path)
end
def create
puts "Your file is empty."
file = File.new(@file_path, 'w')
file.close
end
def file_to_array(path)
# read file content into an array
array = []
if file_exist?
File.open(path, 'r') do |file|
file.each_line do |line|
array << line.strip
end
end
else
create
end
array
end # file_to_array
def array_to_file(array)
File.open(@file_path, 'w') do |file|
array.each do |line|
file.puts line
end
end
end
end