Ruby Shoes: counting the number of times that matters in an array

I make Yahtzee game in Ruby with shoes when I press the "Two" button, the code should count the number of times the value 2 occurs in the array. For each instance of the value 2 that appears, the score is increased by 2.

This code works for the selected number of cases, but in other cases, such as @array = [2,1,2,2,3] # there are three 2 in the array, so the rating should be 6, but instead, my code returns 4. .. why?

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
+3
source share
2 answers

This code looks better, but actually it does the same. Perhaps you should check the initial values โ€‹โ€‹of the instance variables @scoreand @points?

@array = [2,1,2,2,3]

@score = @points = 0

@score = @array.count(2) * 2
@points = @score

@score
 => 6 
@points
 => 6
+6

Enumerable # inject. inject :

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

. !

0

All Articles