use*_*983 3 ruby arrays indexing shoes duplicates
当我点击Button"Two"时,我正在Ruby中使用Shoes制作一个Yahtzee游戏,代码假定计算值2在数组中出现的次数.对于出现的值2的每个实例,分数增加2.
此代码适用于一定数量的案例,但在其他情况下,如@array = [2,1,2,2,3]#数组中有三个2,因此得分为6,但我的代码返回4 ...为什么?
button " twos " do
@array.each_with_index do |value, index|
if (@array[index] == 2)
@score = @score + 2
@points = @score + 2
end #if
end #loop end #button
Run Code Online (Sandbox Code Playgroud)
这段代码看起来更好,但实际上它做了同样的事情.也许你应该检查实例变量的初始值@score和@points?
@array = [2,1,2,2,3]
@score = @points = 0
@score = @array.count(2) * 2
@points = @score
@score
=> 6
@points
=> 6
Run Code Online (Sandbox Code Playgroud)