Reputation: 892
I'm getting this error when trying to SUM up each boxes.percent
into local variable percent
.
Here is error:
no implicit conversion of Fixnum into Array
My code:
<% percent = 0, shares = 0 %>
<% @modification.boxes.each do |d|
percent = percent + d.percent #here is problem, at least rails told me that
shares = shares + d.shares
end %>
<% unless percent == 100 %>
Total percent needs to be 100%!
<% end %>
<% unless shares == @modification.entity.total_number %>
Not correct number!
<% end %>
Where is the problem? In database both percent
and shares
for boxes are integer.
Upvotes: 1
Views: 74
Reputation: 114238
The assignment doesn't work as you expect:
percent = 0, shares = 0
because it is interpreted as:
percent = (0, (shares = 0))
which is equivalent to:
shares = 0
percent = 0, shares
The last line implicitly creates an array. You could also write:
shares = 0
percent = [0, shares]
The "fix" is actually simple. You have to move the variables to the left-hand side and the values to the right-hand side:
percent, shares = 0, 0
This is called multiple assignment.
BTW, instead of looping yourself, you could also use sum
:
percent = @modification.boxes.sum(&:percent)
shares = @modification.boxes.sum(&:shares)
Upvotes: 1
Reputation: 2767
Here is your problem:
You are declaring percent
and shares
as percent = 0, shares = 0
. This will create percent as Array
with value [0,0]
.
Rather declare both as percent = 0; shares = 0
. (notice the semicolon instead of comma)
2.1.5 :042 > percent = 0, shares = 0
=> [0, 0]
2.1.5 :043 > percent
=> [0, 0]
2.1.5 :044 > percent.class
=> Array
Upvotes: 3