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

Ruby查找以ing结尾单词的代码出现NoMethodError报错求助

问题排查与解决

错误原因

Ruby的String类没有last方法(该方法属于Array类),所以调用word.last(3)会触发NoMethodError。

解决方案

有两种常用方式可以实现需求:

方法1:使用end_with?(推荐,最简洁)

Ruby字符串内置了end_with?方法,专门用于判断字符串是否以指定后缀结尾:

def find_all_words_ending_in_ing
  words = ["bring", "finger", "drought", "singing", "bingo", "purposeful"]
  words.find_all do |word|
    word.end_with?("ing")
  end
end

甚至可以简化成一行:

def find_all_words_ending_in_ing
  ["bring", "finger", "drought", "singing", "bingo", "purposeful"].find_all { |w| w.end_with?("ing") }
end

方法2:使用字符串切片

如果需要手动截取末尾字符,可以用字符串的切片语法[-3..-1]获取最后3个字符(注意要处理长度不足3的单词,避免报错):

def find_all_words_ending_in_ing
  words = ["bring", "finger", "drought", "singing", "bingo", "purposeful"]
  words.find_all do |word|
    word.length >= 3 && word[-3..-1] == "ing"
  end
end

额外说明

你原代码里的new_word数组是冗余的——find_all方法本身会返回所有满足条件的元素组成的数组,不需要手动收集结果。

内容的提问来源于stack exchange,提问作者Günther Schatz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 03:39:58