You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:54:00