I have written this code to determine how many a's are present in a given input within a method:
def count_a(word)
count = 0
i = 0
while i < word.length
char = word[i]
if char == "a" || char == "A"
count += 1
end
i += 1
end
return count
end
puts count_a("application") # => 2
puts count_a("bike") # => 0
puts count_a("Arthur") # => 1
puts count_a("Aardvark") # => 3
Can someone better explain why I need the i += 1 at the bottom of the method? I have added to the count in the conditional above, so I just need some further knowledge on how the iteration becomes necessary outside the conditional and within the method.
Thanks!
The code failed to run without the i += 1
char.downcase == 'a'orcase charandwhen /\Aa\z/iwhich ignores case.i, the variable would always have the value 0, and the condition forwhilewould always be true, leaving you with an infinite loop.