我正在摆弄一些关于红宝石的实践问题,这些问题来自APP学院的录取。我无法理解为什么我的解决方案无法正常工作的一个特殊问题。
问题
# Write a method that takes a string and returns the number of vowels
# in the string. You may assume that all the letters are lower cased.
# You can treat "y" as a consonant.
这是我未通过测试的解决方案的代码。
def count_vowels(string)
vowels = 0
word = string.split()
idx = 0
while idx <= word.length
current_char = word[idx]
if (current_char == "a"||current_char =="e"||current_char=="i"||current_char=="o"||current_char=="u")
vowels += 1
end
idx += 1
end
return vowels
end
这是可行的解决方案。
def count_vowels(string)
num_vowels = 0
i = 0
while i < string.length
if (string[i] == "a" || string[i] == "e" || string[i] == "i" || string[i] == "o" || string[i] == "u")
num_vowels += 1
end
i += 1
end
return num_vowels
end
答案 0 :(得分:2)
在Ruby中,默认情况下,String#split
在空格上将字符串拆分为单词:
"test string split".split() # => ["test", "string", "split"]
因此,您的解决方案是计算等于元音的完整单词的数量(单词本身例如“ a”和“ I”)。如果您通过将''
作为参数传递给split
来拆分成字符,则您的代码将起作用:
"test string split".split('') # => ["t", "e", "s", "t", " ",
"s", "t", "r", "i", "n", "g", " ", "s", "p", "l", "i", "t"]
但是,有更好的方法来获取字符串中的每个字符,例如String#each_char
:
"test string split".each_char { |char| # increment counter if char is a vowel }
接下来,您可以简单地使用String#count
来计算元音的数量:
"test string split".count('aeiou') # => 3
答案 1 :(得分:1)
如上面的评论中所述,您可以使用String的count
方法来简化实现:
def count_vowels(string)
string.count('aeiou')
end
答案 2 :(得分:0)
在您的代码中,它应该为word = string.split("")
以上代码段将字符串拆分为一个数组。