回答編集履歴
4
sum加筆
answer
CHANGED
@@ -39,4 +39,20 @@
|
|
39
39
|
@ob = @contents.map(&:ob).reduce(&:+)
|
40
40
|
@water = @contents.map(&:water).reduce(&:+)
|
41
41
|
end
|
42
|
+
```
|
43
|
+
|
44
|
+
しかしここでは、ActiveRecordの`sum`を使うのが一番スッキリするでしょう。
|
45
|
+
|
46
|
+
```ruby
|
47
|
+
def edit
|
48
|
+
@game = Game.find(params[:id])
|
49
|
+
@contents = Content.where(game_id:params[:id])
|
50
|
+
|
51
|
+
@putts = @contents.sum(:putt)
|
52
|
+
@score = @contents.sum(:score)
|
53
|
+
@par = @contents.sum(:par)
|
54
|
+
@ob = @contents.sum(:ob)
|
55
|
+
@water = @contents.sum(:water)
|
56
|
+
end
|
57
|
+
```
|
42
58
|
```
|
3
バグfix
answer
CHANGED
@@ -33,10 +33,10 @@
|
|
33
33
|
@game = Game.find(params[:id])
|
34
34
|
@contents = Content.where(game_id:params[:id])
|
35
35
|
|
36
|
-
@putts = @contents.
|
36
|
+
@putts = @contents.map(&:putt).reduce(&:+)
|
37
|
-
@score = @contents.
|
37
|
+
@score = @contents.map(&:score).reduce(&:+)
|
38
|
-
@par = @contents.
|
38
|
+
@par = @contents.map(&:par).reduce(&:+)
|
39
|
-
@ob = @contents.
|
39
|
+
@ob = @contents.map(&:ob).reduce(&:+)
|
40
|
-
@water = @contents.
|
40
|
+
@water = @contents.map(&:water).reduce(&:+)
|
41
41
|
end
|
42
42
|
```
|
2
reduce ver
answer
CHANGED
@@ -25,4 +25,18 @@
|
|
25
25
|
@water += content.water
|
26
26
|
end
|
27
27
|
end
|
28
|
+
```
|
29
|
+
|
30
|
+
さらに、`reduce`(`inject`)を使うと、ここでは初期化も不要なので以下のように書くこともできます。
|
31
|
+
```ruby
|
32
|
+
def edit
|
33
|
+
@game = Game.find(params[:id])
|
34
|
+
@contents = Content.where(game_id:params[:id])
|
35
|
+
|
36
|
+
@putts = @contents.reduce(&:putt)
|
37
|
+
@score = @contents.reduce(&:score)
|
38
|
+
@par = @contents.reduce(&:par)
|
39
|
+
@ob = @contents.reduce(&:ob)
|
40
|
+
@water = @contents.reduce(&:water)
|
41
|
+
end
|
28
42
|
```
|
1
多重代入も追加
answer
CHANGED
@@ -5,17 +5,17 @@
|
|
5
5
|
```ruby
|
6
6
|
@putts += content.putt
|
7
7
|
```
|
8
|
+
のようにも書けますし、初期化も多重代入を使うと
|
9
|
+
```
|
10
|
+
@putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
|
11
|
+
```
|
8
|
-
のように
|
12
|
+
のように書けるので、それらを使うと下のように少しスッキリ書くことができます。
|
9
13
|
|
10
14
|
```ruby
|
11
15
|
def edit
|
12
16
|
@game = Game.find(params[:id])
|
13
17
|
@contents = Content.where(game_id:params[:id])
|
14
|
-
@putts = 0
|
18
|
+
@putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
|
15
|
-
@score = 0
|
16
|
-
@par = 0
|
17
|
-
@ob = 0
|
18
|
-
@water = 0
|
19
19
|
|
20
20
|
@contents.each do |content|
|
21
21
|
@putts += content.putt
|