![](/img/trans.png)
[英]Sorting a Ruby array of hashes based on the amount of times a value appears
[英]Ruby Shoes: counting the amount of times a value occurs in an Array
當我點擊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
這段代碼看起來更好,但實際上它做了同樣的事情。 也許你應該檢查實例變量@score
和@points
初始值?
@array = [2,1,2,2,3]
@score = @points = 0
@score = @array.count(2) * 2
@points = @score
@score
=> 6
@points
=> 6
我建議你使用Enumerable #injection方法。 通過注入,您可以實現抽象方法來計算數字並在項目的任何位置使用它:
def count_of_element array, element
array.inject(0) { |count, e| count += 1 if e == element; count }
end
puts count_of_element [2,1,2,2,3], 2 # => 3
可能有更好的解決方案 - 為這樣的Array類定義方法:
class Array
def count_of_element element
inject(0) { |count, e| count += 1 if e == element; count }
end
end
puts [2,1,2,2,3].count_of_element 2 # => 3
它看起來更酷。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.