Count matching array values using each

I’m just now learning Ruby. I have an array of numbers, and then a
single number stored as a variable. I’m trying to use the each method
to evaluate each value in the array and count how many match my
variable. I’m expecting 2, but I keep getting 0, no Ruby errors, just
returns zero. Any ideas how do accomplish this with the each method?

numArray = [3,1,4,1,5,9,2,6,3,5]
n = 5
count = 0
def nCounter
numArray.each do |countnum|
if countnum == n
count = count + 1
else
end
end
nCounter
end
puts “Your number matches " + count.to_s + " times”

Jamie F. wrote in post #1158147:

I’m just now learning Ruby. I have an array of numbers, and then a
single number stored as a variable. I’m trying to use the each method
to evaluate each value in the array and count how many match my
variable. I’m expecting 2, but I keep getting 0, no Ruby errors, just
returns zero. Any ideas how do accomplish this with the each method?

You can check what is happening by putting a print statement within the
loop:

numArray = [3,1,4,1,5,9,2,6,3,5]
n = 5
count = 0
def nCounter
numArray.each do |countnum|
puts “in loop”
if countnum == n
count = count + 1
else
end
end
nCounter
end
puts “Your number matches " + count.to_s + " times”

You’ll see the ‘in loop’ message is not printed. The checking operation
is not being performed because it is within a method ‘nCounter’ which is
not called.

Try simply:

numArray = [3,1,4,1,5,9,2,6,3,5]
n = 5
count = 0
numArray.each do |countnum|
if countnum == n
count = count + 1
else
end
end
puts “Your number matches " + count.to_s + " times”

Thanks. Is there any way to do this using the defined method (nCounter
in this case)?

Jamie F. wrote in post #1158173:

Thanks. Is there any way to do this using the defined method (nCounter
in this case)?

For your method to work, you need to pass in the array and target number
as parameters. You could do:

def nCounter(numArray, n)
count = 0

numArray.each do |countnum|
if countnum == n
count = count + 1
else
end
end

return count
end

numArray = [3,1,4,1,5,9,2,6,3,5]
n = 5
count = nCounter(numArray, n)

puts “Your number matches " + count.to_s + " times”