def count_vowels(string)
count_vowels = 0
my_vowels = ["a" "e" "i" "o" "u"]
idx = 0
while idx < string.length
gdx = 0
while gdx < my_vowels.length
if string[idx] == my_vowels[gdx]
count_vowels = count_vowels + 1
else
gdx = gdx + 1
end
end
idx = idx + 1
end
return count_vowels
end
while gdx < my_vowels.length
if string[idx] == my_vowels[gdx]
count_vowels = count_vowels + 1
else
gdx = gdx + 1
end
end
应该:
while gdx < my_vowels.length
if string[idx] == my_vowels[gdx]
count_vowels = count_vowels + 1
gdx = gdx + 1
else
gdx = gdx + 1
end
end
因为你在找到元音后没有推进你的gdx计数器。所以它在找到第一个元音后最终会循环。
同样修复数组声明,工作代码可能是这样的:
def count_vowels(string)
count_vowels = 0
my_vowels = ["a", "e", "i","o","u","y"]
idx = 0
while idx < string.length
gdx = 0
while gdx < my_vowels.length
if string[idx] == my_vowels[gdx]
count_vowels = count_vowels + 1
gdx=gdx+1
else
gdx = gdx + 1
end
end
idx = idx + 1
end
def count_vowels(str)
str.downcase.count("aeiou")
end
count_vowels("All the king's horses and all the king's men...")
#=> 10
试试这种方法
def count_vowels(string)
['a', 'e', 'i', 'o', 'u'].inject(0) { |sum, el| sum += string.downcase.count(el) }
end
请注意我为输入字符串做了downcase
以减少迭代量。如果你有另一个逻辑 - 只需删除它。