回答編集履歴
1
追加
test
CHANGED
@@ -19,3 +19,77 @@
|
|
19
19
|
|
20
20
|
|
21
21
|
`args[:library] << self`が、`Book`の`initialize`にあるので、`Book`オブジェクトを作る度にその引数で指定したライブラリーに追加することになります。
|
22
|
+
|
23
|
+
|
24
|
+
|
25
|
+
#追記
|
26
|
+
|
27
|
+
演算子メソッドの定義がわかりにくいと言うことであれば、下記でも同じです。
|
28
|
+
|
29
|
+
```Ruby
|
30
|
+
|
31
|
+
class Library
|
32
|
+
|
33
|
+
def initialize
|
34
|
+
|
35
|
+
@books = []
|
36
|
+
|
37
|
+
end
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
def add(book)
|
42
|
+
|
43
|
+
@books << book
|
44
|
+
|
45
|
+
end
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
def to_s
|
50
|
+
|
51
|
+
puts "Library contents:"
|
52
|
+
|
53
|
+
@books.join("\n")
|
54
|
+
|
55
|
+
end
|
56
|
+
|
57
|
+
end
|
58
|
+
|
59
|
+
|
60
|
+
|
61
|
+
class Book
|
62
|
+
|
63
|
+
attr_accessor :author, :title
|
64
|
+
|
65
|
+
def initialize(args)
|
66
|
+
|
67
|
+
@author = args[:author]
|
68
|
+
|
69
|
+
@title = args[:title]
|
70
|
+
|
71
|
+
args[:library].add(self)
|
72
|
+
|
73
|
+
end
|
74
|
+
|
75
|
+
|
76
|
+
|
77
|
+
def to_s
|
78
|
+
|
79
|
+
"Title: " + @title + ", Author: " + @author
|
80
|
+
|
81
|
+
end
|
82
|
+
|
83
|
+
end
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
my_library = Library.new
|
88
|
+
|
89
|
+
Book.new(:author => "Herman Melville", :title => "Moby-Dick", :library => my_library)
|
90
|
+
|
91
|
+
Book.new(:author => "Hans Christian Andersen", :title => "The Ugly Duckling", :library => my_library)
|
92
|
+
|
93
|
+
puts my_library
|
94
|
+
|
95
|
+
```
|