我的代码找到元音的数量不起作用

时间:2018-02-28 19:18:46

标签: ruby

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

3 个答案:

答案 0 :(得分:1)

def count_vowels(str)
  str.downcase.count("aeiou")
end

count_vowels("All the king's horses and all the king's men...")
  #=> 10

答案 1 :(得分:0)

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

答案 2 :(得分:0)

尝试这种方法

def count_vowels(string)
  ['a', 'e', 'i', 'o', 'u'].inject(0) { |sum, el| sum += string.downcase.count(el) }
end

请注意我输入字符串downcase以减少迭代次数。如果你有另一个逻辑 - 只需删除它。