回答編集履歴
4
例の追加に伴い、説明を変更
answer
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
|
1
|
+
配下の全レコードを集めるほうが、よりシンプルで、使い勝手も良さそう。
|
2
2
|
|
3
3
|
```ruby
|
4
4
|
# インスタンスメソッドとして実現
|
3
関数として実装した場合を追加
answer
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
レコードを表すクラスに、配下の全レコードを取り出すメソッドを追加するのも良いかもしれない。
|
2
2
|
|
3
3
|
```ruby
|
4
|
+
# インスタンスメソッドとして実現
|
4
5
|
class Record
|
5
6
|
def all_records
|
6
7
|
[self, *subs.flat_map(&:all_records)]
|
@@ -8,4 +9,14 @@
|
|
8
9
|
end
|
9
10
|
|
10
11
|
@item.all_records.map(&:id)
|
12
|
+
|
13
|
+
# 関数として実現
|
14
|
+
def collect_records(recode)
|
15
|
+
[
|
16
|
+
recode,
|
17
|
+
*recode.subs.flat_map { |sub_recode| collect_records(sub_recode) }
|
18
|
+
]
|
19
|
+
end
|
20
|
+
|
21
|
+
collect_records(@item).map(&:id)
|
11
22
|
```
|
2
select を削除
answer
CHANGED
@@ -7,6 +7,5 @@
|
|
7
7
|
end
|
8
8
|
end
|
9
9
|
|
10
|
-
@item.all_records
|
10
|
+
@item.all_records.map(&:id)
|
11
|
-
.select { |record| record.respond_to?(:id) }.map(&:id)
|
12
11
|
```
|
1
タイポを修正
answer
CHANGED
@@ -3,7 +3,7 @@
|
|
3
3
|
```ruby
|
4
4
|
class Record
|
5
5
|
def all_records
|
6
|
-
[self, *subs.flat_map(&:
|
6
|
+
[self, *subs.flat_map(&:all_records)]
|
7
7
|
end
|
8
8
|
end
|
9
9
|
|