在ruby中查找以“ing”结尾的所有单词

mzillmmw  于 2023-05-17  发布在  Ruby
关注(0)|答案(3)|浏览(120)
def find_all_words_ending_in_ing
  words = ["bring", "finger", "drought", "singing", "bingo", "purposeful"]
  new_word = []
  # Your code goes here
  words.find_all do |word|
    if word.last(3) == "ing"
      new_word << word
    end
  end
  new_word
  #  expected return value is ["bring", "singing"]
end

代码需要迭代数组中的项,并输出以“ing”结尾的单词
我得到这个错误:

undefined method `last' for "bring":String (NoMethodError)
      if word.last(3) == "ing"
              ^^^^
o2rvlv0m

o2rvlv0m1#

String没有last()方法,但String有end_with?方法。
示例:

words.select do |word|
  word.end_with? "ing"
end
jmp7cifd

jmp7cifd2#

如果你不害怕正则表达式,有一个很好的工具,叫做grep,它的工作方式很像1同名的命令行工具:

words.grep(/ing\z/)

这里\z在Ruby regexp表示法中表示“字符串结束”。

1它的功能远不止匹配字符串,因为它利用了===运算符,所以它比你想象的更方便!

nimxete2

nimxete23#

我建议你使用#select#end_with?代替。

["bring", "finger", "drought", "singing", "bingo", "purposeful"].select { |s| 
  s.end_with? "ing" 
}

在执行 your 代码时,我们看到以下错误。

Traceback (most recent call last):
        8: from /usr/local/bin/irb:23:in `<main>'
        7: from /usr/local/bin/irb:23:in `load'
        6: from /var/lib/gems/2.5.0/gems/irb-1.2.0/exe/irb:11:in `<top (required)>'
        5: from (irb):31
        4: from (irb):23:in `find_all_words_ending_in_ing'
        3: from (irb):23:in `find_all'
        2: from (irb):23:in `each'
        1: from (irb):24:in `block in find_all_words_ending_in_ing'
NoMethodError (undefined method `last' for "bring":String)

如果查看documentation for the String class,则不存在#last方法,这正是错误所告诉您的。
但是,#end_with?将接受一个字符串,并检查该字符串是否是调用该方法的字符串的后缀。
要忽略数组中字符串的任何尾随空格,您可能希望使用#rstrip

["bring", "finger", "drought", "singing", "bingo", "purposeful"].select { |s| 
  s.rstrip.end_with? "ing" 
}

如果你不关心大小写,那么你可以将字符串小写:

["bring", "WING", "finger", "drought", "singing", "bingo", "purposeful"].select { |s| 
  s.rstrip.downcase.end_with? "ing" 
}

或者使用正则表达式:

["bring", "WING", "finger", "drought", "singing", "bingo", "purposeful"].select { |s| 
  s =~ /ing\s*\Z/i
}

或者使用另外提到的#grep

["bring", "WING", "finger", "drought", "singing", "bingo", "purposeful"].grep(/ing\s*\Z/i)

相关问题