Ruby consonant_cancel方法输出不符合预期 求调试帮助
问题排查与修复
问题根因
你的代码没有在匹配到单词第一个元音后终止遍历,每个单词内每遇到一个元音就会往结果数组插入一次子串,最终结果会包含大量多余片段:比如单词writing包含两个元音i,就会同时插入iting和ing两个片段,和预期的每个单词只保留第一个元音开头的片段不符。
修复方案
匹配到单词第一个元音后,插入对应子串就直接跳出当前单词的字符遍历即可,修改后的代码如下:
def consonant_cancel(sentence) arr = [] vowels = 'aeiou' words = sentence.split words.each do |word| word.each_char.with_index do |char, i| if vowels.include?(char) arr << word[i..-1] break # 找到第一个元音后直接跳出,不再遍历后续字符 end end end return arr.join(' ') end
验证结果
运行测试用例:
puts consonant_cancel("down the rabbit hole")输出own e abbit ole,符合预期puts consonant_cancel("writing code is challenging")输出iting ode is allenging,符合预期
内容的提问来源于stack exchange,提问作者harderfasterstronger
相关产品推荐
相关产品推荐

