我的Ruby元音计数循环出了什么问题?

时间:2016-11-29 22:56:52

标签: ruby string loops

我正在尝试创建一个循环,每次在字符串中添加一个元音 idx 时,我的代码都不返回任何内容。

def count_vowels(string)
  vowlcounter = 0 
  idx = 0 
  words = string.split('')

  while idx < string.length 
    if words[idx] == 'a'||'e'||'i'||'o'||'u'
      vowlcounter += 1 
      idx += 1
    end
  end

  return vowlcounter
end

2 个答案:

答案 0 :(得分:3)

如果字符串或char是元音,则可以使用正则表达式进行较短的比较。你希望的另一种方式太长了:

if words[idx] == 'a' || words[idx] == 'e'

等等......

此外,如果你每次实际有一个元音时只增加idx,如果char不是元音,你将陷入无限循环,idx不会增加,因此总是检查while循环中的值相同。

此代码使用正则表达式:

def count_vowels(string)
  vowlcounter = 0 
  idx = 0

  while idx < string.length
    if string[idx][/[aeiou]/]
      vowlcounter += 1;
    end
    idx += 1;
  end
  return vowlcounter
end

答案 1 :(得分:2)

扫描和计数元音

X/Y problem令我感到震惊。而不是调试代码,最好只使用内置的String方法来计算元音,而不是通过字符串进行自己的迭代。其他人可以解决你的X / Y问题中的Y,但我宁愿帮你直接解决X.

使用String#scan

使用String#scanArray#count快速轻松地完成此操作。虽然这在用作元音时不会考虑y,但它应该做你想要的。

def vowel_count str 
  str.scan(/[aeiou]/).count
end

vowel_count 'foo'
#=> 2

vowel_count 'foo bar baz'
#=> 4

使用字符串#count

我最喜欢使用#scan,因为它返回一个你可以在其他地方使用的数组,如果你喜欢并帮助调试。但是,如果您不关心找到哪些元音,则可以直接使用String#count方法。例如:

def vowel_count str
  str.count 'aeiou'
end

vowel_count 'foo'
#=> 2

vowel_count 'foo bar baz'
#=> 4

结果是一样的,但是你无法反省方法中返回的值。 YMMV。