-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirectory.rb
92 lines (81 loc) · 1.93 KB
/
directory.rb
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
@students = [] # an empty array accessible to all methods
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
# get the first name
name = gets.chomp
# while the name is not empty, repeat this code
while !name.empty? do
# add the student hash to the array
@students << {name: name, cohort: :november}
puts "Now we have #{@students.count} students"
# get another name from the user
name = gets.chomp
end
end
def interactive_menu
loop do
print_menu
process(gets.chomp)
end
end
def print_menu
puts "1. Input the students"
puts "2. Show the students"
puts "3. Save the list to students.csv"
puts "4. Loads the list from students.csv"
puts "9. Exit" # 9 because we'll be adding more items
end
def show_students
print_header
print_student_list
print_footer
end
def process(selection)
case selection
when "1"
input_students
when "2"
show_students
when "3"
save_students
when "4"
load_students
when "9"
exit # this will cause the program to terminate
else
puts "I don't know what you meant, try again"
end
end
def print_header
puts "The students of Villains Academy"
puts "-------------"
end
def print_student_list
@students.each do |student|
puts "#{student[:name]} (#{student[:cohort]} cohort)"
end
end
def print_footer
puts "Overall, we have #{@students.count} great students"
end
def save_students
# open the file for writing
file = File.open("students.csv", "w")
# iterate over the array of students
@students.each do |student|
student_data = [student[:name], student[:cohort]]
csv_line = student_data.join(",")
file.puts csv_line
end
file.close
end
def load_students
file = File.open("students.csv", "r")
file.readlines.each do |line|
name, cohort = line.chomp.split(',')
@students << {name: name, cohort: cohort.to_sym}
end
file.close
end
interactive_menu