回答編集履歴
4
sum加筆
test
CHANGED
@@ -81,3 +81,35 @@
|
|
81
81
|
end
|
82
82
|
|
83
83
|
```
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
しかしここでは、ActiveRecordの`sum`を使うのが一番スッキリするでしょう。
|
88
|
+
|
89
|
+
|
90
|
+
|
91
|
+
```ruby
|
92
|
+
|
93
|
+
def edit
|
94
|
+
|
95
|
+
@game = Game.find(params[:id])
|
96
|
+
|
97
|
+
@contents = Content.where(game_id:params[:id])
|
98
|
+
|
99
|
+
|
100
|
+
|
101
|
+
@putts = @contents.sum(:putt)
|
102
|
+
|
103
|
+
@score = @contents.sum(:score)
|
104
|
+
|
105
|
+
@par = @contents.sum(:par)
|
106
|
+
|
107
|
+
@ob = @contents.sum(:ob)
|
108
|
+
|
109
|
+
@water = @contents.sum(:water)
|
110
|
+
|
111
|
+
end
|
112
|
+
|
113
|
+
```
|
114
|
+
|
115
|
+
```
|
3
バグfix
test
CHANGED
@@ -68,15 +68,15 @@
|
|
68
68
|
|
69
69
|
|
70
70
|
|
71
|
-
@putts = @contents.reduce(&:
|
71
|
+
@putts = @contents.map(&:putt).reduce(&:+)
|
72
72
|
|
73
|
-
@score = @contents.reduce(&:
|
73
|
+
@score = @contents.map(&:score).reduce(&:+)
|
74
74
|
|
75
|
-
@par = @contents.reduce(&:
|
75
|
+
@par = @contents.map(&:par).reduce(&:+)
|
76
76
|
|
77
|
-
@ob = @contents.reduce(&:
|
77
|
+
@ob = @contents.map(&:ob).reduce(&:+)
|
78
78
|
|
79
|
-
@water = @contents.reduce(&:
|
79
|
+
@water = @contents.map(&:water).reduce(&:+)
|
80
80
|
|
81
81
|
end
|
82
82
|
|
2
reduce ver
test
CHANGED
@@ -53,3 +53,31 @@
|
|
53
53
|
end
|
54
54
|
|
55
55
|
```
|
56
|
+
|
57
|
+
|
58
|
+
|
59
|
+
さらに、`reduce`(`inject`)を使うと、ここでは初期化も不要なので以下のように書くこともできます。
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
|
63
|
+
def edit
|
64
|
+
|
65
|
+
@game = Game.find(params[:id])
|
66
|
+
|
67
|
+
@contents = Content.where(game_id:params[:id])
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
@putts = @contents.reduce(&:putt)
|
72
|
+
|
73
|
+
@score = @contents.reduce(&:score)
|
74
|
+
|
75
|
+
@par = @contents.reduce(&:par)
|
76
|
+
|
77
|
+
@ob = @contents.reduce(&:ob)
|
78
|
+
|
79
|
+
@water = @contents.reduce(&:water)
|
80
|
+
|
81
|
+
end
|
82
|
+
|
83
|
+
```
|
1
多重代入も追加
test
CHANGED
@@ -12,7 +12,15 @@
|
|
12
12
|
|
13
13
|
```
|
14
14
|
|
15
|
+
のようにも書けますし、初期化も多重代入を使うと
|
16
|
+
|
17
|
+
```
|
18
|
+
|
19
|
+
@putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
|
20
|
+
|
21
|
+
```
|
22
|
+
|
15
|
-
のように
|
23
|
+
のように書けるので、それらを使うと下のように少しスッキリ書くことができます。
|
16
24
|
|
17
25
|
|
18
26
|
|
@@ -24,15 +32,7 @@
|
|
24
32
|
|
25
33
|
@contents = Content.where(game_id:params[:id])
|
26
34
|
|
27
|
-
@putts = 0
|
35
|
+
@putts, @score, @par, @ob, @water = 0, 0, 0, 0, 0
|
28
|
-
|
29
|
-
@score = 0
|
30
|
-
|
31
|
-
@par = 0
|
32
|
-
|
33
|
-
@ob = 0
|
34
|
-
|
35
|
-
@water = 0
|
36
36
|
|
37
37
|
|
38
38
|
|