3

I'm making a Yahtzee game in Ruby using Shoes when I click Button "Two" the code is suppose to count the amount of times the value 2 occurs in an array. For every instance of the value 2 that appears, the score is incremented by 2.

This code works for a select amount of cases but on other cases like @array = [2,1,2,2,3] # there are three 2's in the array so the score is suppose to 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

2 Answers2

6

This code looking better, but, in fact, it does the same thing. Maybe you should check initial values of instance variables @score and @points?

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

@score = @points = 0

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

@score
 => 6 
@points
 => 6
Flexoid
  • 4,155
  • 21
  • 20
  • so I tried this code, when I got to @array = [2,4,2,2,4] it gave me a score of 2- why might this be? – user1391983 May 13 '12 at 09:36
  • If you try this code in the clean environment, irb, for example, it returns you 6. So I think the problem in the part of code that you didn't show. PS. now code looking even better) – Flexoid May 13 '12 at 09:39
  • hmm other than printing out the score using title, all the code I used in relation to @score is the same as yours, and when I print out the array it prints out the correct array. Thank you for your help though! it is greatly appreciated! – user1391983 May 13 '12 at 09:43
  • 1
    I think it might help if you make lightweight version of your program, including only code needed to calculate and print out score, and then check how it will work. – Flexoid May 13 '12 at 09:47
  • Are you certain that the objects are equal? I mean might some of the 2s be "2"s? Please go through all of your elements and check ifputs "#{@array[index]}: #{@array[index] == 2}" – ayckoster May 13 '12 at 11:28
0

I recommend you to use Enumerable#inject method. By means of inject you can implement abstract method for counting numbers and use it everywhere in your project:

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

There could be even better solution – define method for Array class like this:

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

It looks even cooler. Good luck!

makaroni4
  • 2,281
  • 1
  • 18
  • 26
  • Eeh, as you could see from Flexoid's solution, the `count` method exists already. No need to define your own. – Mischa May 13 '12 at 14:06