forked from gisborne/ruby-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruby-hash-exercise2-answer.rb
102 lines (92 loc) · 2 KB
/
ruby-hash-exercise2-answer.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
93
94
95
96
97
98
99
100
101
102
@favorite_books = {
'Frank Herbert' => ['Dune', 'Dune Messiah', 'Children of Dune', 'God Emperor of Dune'],
'Isaac Asimov' => ['Foundation', 'Foundation and Empire', 'Second Foundation'],
'Mervyn Peake' => ['Titus Groan', 'Gormenghast'],
'William Goldman' => ['The Princess Bride']
}
def get_books author
books = @favorite_books[author]
if books == nil
puts "No such author"
else
puts books.join ', '
end
end
def count_books author
books = @favorite_books[author]
if books == nil
puts "No such author"
else
puts books.length
end
end
def find book
result = nil
@favorite_books.each do |author, books|
if books.include? book
result = author
end
end
if result
puts result
else
puts "No such book"
end
end
def add_book author, title
books = @favorite_books[author]
if books
if books.include? title
puts "That book is already in the system"
else
books << title
end
else
puts "No such author"
end
end
def delete_book author, title
books = @favorite_books[author]
if books
if books.include? title
books.delete title
else
puts "No such title"
end
else
puts "No such author"
end
end
def handle_command command, arg
if command == 'get'
get_books arg
elsif command == 'count'
count_books arg
elsif command == 'find'
find arg
elsif command == 'add'
args = arg.split ',', 2
if args.length == 2
#strip removes blanks from beginning and end of string
add_book args[0].strip, args[1].strip
else
"No book title provided"
end
elsif command == 'delete'
args = arg.split ',', 2
if args.length == 2
delete_book args[0].strip, args[1].strip
else
"No book title provided"
end
else
puts "Command not recognized"
end
end
loop do
print "Enter a command (q to finish): "
entered = gets.chomp
exit if entered == 'q'
parts = entered.split ' ', 2 #Split into two parts
handle_command parts[0], parts[1]
end