我怎么算元音?

我已经看到了解决方案,它或多或少匹配

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. Difficulty: easy. def count_vowels(string) vowel = 0 i = 0 while i < string.length if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u") vowel +=1 end i +=1 return vowel end puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}") puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}") puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}") puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}") 

 def count_vowels(str) str.scan(/[aeoui]/).count end 

/[aeoui]/是一个正则表达式,基本上意味着“任何这些字符:a,e,o,u,i”。 String#scan方法返回String#scan则表达式的所有匹配项。

 def count_vowels(str) str.count("aeoui") end 

你的function很好,你只是错过了关闭你的while循环的关键字

 def count_vowels(string) vowel = 0 i = 0 while i < string.length if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u") vowel +=1 end i +=1 end return vowel end puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}") puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}") puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}") puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}") #=> count_vowels("abcd") == 1: true #=> count_vowels("color") == 2: true #=> count_vowels("colour") == 3: true #=> count_vowels("cecilia") == 4: true 

我认为使用HashTable数据结构将是解决这个特定问题的好方法。 特别是如果你需要分别输出每个元音的数量。

这是我使用的代码:

 def vowels(string) found_vowels = Hash.new(0) string.split("").each do |char| case char.downcase when 'a' found_vowels['a']+=1 when 'e' found_vowels['e']+=1 when 'i' found_vowels['i']+=1 when 'o' found_vowels['o']+=1 when 'u' found_vowels['u']+=1 end end found_vowels end p vowels("aeiou") 

甚至这个(优雅但不一定高性能):

 def elegant_vowels(string) found_vowels = Hash.new(0) string.split("").each do |char| case char.downcase when ->(n) { ['a','e','i','o','u'].include?(n) } found_vowels[char]+=1 end end found_vowels end p elegant_vowels("aeiou") 

哪个会输出:

{“a”=> 1,“e”=> 1,“i”=> 1,“o”=> 1,“u”=> 1}

因此,您不必将字符串转换为数组并担心区分大小写:

 def getVowelCount(string) string.downcase.count 'aeiou' end