Ruby block `block in Method': undefined method `inject&#



我有一个方法,它接受一个字符串并返回一个新的句子字符串,其中每个长度超过 4 个字符的单词都删除了所有元音。输出应返回修改后的句子字符串到这些规范。

def abbreviate_sentence(sent)
arr = []
word = sent.split("")
word.reject do |v|
if word.length > 4
arr << %w(a e i o u).any?.inject(v)
else arr << word
end
end
return arr
end

我收到以下错误,并尝试将修改后的元素包含/"注入"到一个新数组中,该数组将加入到上述所需字符串中。如果我删除"inject",我会得到一个布尔值,而不是修改后的字符串。

您收到此错误是因为您尝试在 Enumerable#any? 的结果上调用 Enumerable#inject 方法,该方法要么是true,要么是false

其他一些需要注意的小事情:

  • 调用str.split('')将返回所有字符的数组,而不是单词。

  • 要从修改的单词数组中形成结果字符串,可以使用 Array#join 方法


就个人而言,我会通过以下方式解决此任务:

def abbreviate_sentence(sentence)
words = sentence.split # By default this method splits by whitespace
handled_words = words.map do |w|
if w.length > 4
w.tr!('aeiou', '') # This method deltes all the wovels from word
end
w # Handled word
end
handled_words.join(' ') # Ruby returnes last evaluated expression automatically
end

使用irb的一些结果:

abbreviate_sentence 'Hello there! General Kenobi' # => "Hll thr! Gnrl Knb"
abbreviate_sentence 'sample text' # => "smpl text"

我应该指出的一件事: 此方法不保留空格,因为使用了字符串#拆分

abbreviate_sentence "Example n with some ttt new strings n and t tabulations" # => "Exmpl with some new strngs and tbltns"

最新更新