-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.rb
76 lines (63 loc) · 1.58 KB
/
library.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
class Book
attr_reader :title
def initialize(title)
@title = title
end
def enshelf(shelf)
shelf.add_book(self)
end
def unshelf(shelf)
shelf.remove_book(self)
end
end
class Shelf
attr_reader :books
def initialize(lib)
lib.add_shelf(self)
@books = []
end
def remove_book(book)
@books.delete(book) if @books.include?(book) #removes book if on shelf
end
def add_book(book)
@books << book unless @books.include?(book) #adds book if not on shelf
end
def print_books
@books.each { |x| puts x.title } unless @books.empty? #print book titles unless shelf is empty
end
end
class Library
attr_reader :shelves
def initialize
@shelves = []
end
def all_books
@shelves.each { |x| x.print_books } unless @shelves.empty? #calls print_books for each shelf unless shelf is empty
end
def add_shelf(shelf)
@shelves << shelf unless @shelves.include?(shelf) #adds shelf if shelf not already in
end
end
lib = Library.new
puts lib
fiction = Shelf.new(lib)
puts fiction
nonfiction = Shelf.new(lib)
puts nonfiction
book1 = Book.new('East Of Eden')
puts book1.title
book2 = Book.new('A Farewell to Arms')
puts book2.title
book1.enshelf(fiction)
book2.enshelf(fiction)
book3 = Book.new('Principia Mathematica')
book4 = Book.new('A Brief History of Time')
fiction.print_books
nonfiction.print_books
book3.enshelf(nonfiction)
book3.enshelf(nonfiction)
book4.enshelf(nonfiction)
lib.all_books
book3.unshelf(nonfiction)
book3.unshelf(nonfiction)
lib.all_books