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”
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”