首页 > 解决方案 > Ruby块`block in Method':未定义的方法`inject'为true:TrueClass(NoMethodError)

问题描述

我有一个方法,它接受一个字符串并返回一个新的句子字符串,其中每个超过 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

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

标签: rubyruby-on-rails-3

解决方案


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

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

  • 调用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"

我应该指出的一件事:此方法不保留空格,因为使用了String#split

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

推荐阅读