ruby - 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
我收到以下错误,并试图将修改后的元素包含/“注入”到一个新数组中,在该数组中加入上述所需的字符串。如果我删除“注入”,我会得到一个布尔值而不是修改后的字符串。
解决方案
您收到此错误是因为您尝试在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"
我应该指出的一件事:此方法不保留空格,因为使用了String#split
abbreviate_sentence "Example \n with some \t\t\t new strings \n and \t tabulations" # => "Exmpl with some new strngs and tbltns"
推荐阅读
- text - 在特定行中添加/更改数字
- applescript - 如何在typora中使用applescript将markdown导出到html
- javascript - 创建迪士尼尘埃风格的光标轨迹
- java - 使用数组类型参数通过 Class.forName 初始化一个类
- calculated-columns - 识别spotfire中列中的值何时更改
- javascript - Javascript - 不要自动调整无效日期
- java - 在不使用 stringbuilder 或电动工具的情况下随机化和改组字符串
- angular - 点击事件在角度组件内没有响应
- sql-server - 检查备份中的 SQL 配置
- java - 如何解决 Raspberry-Pi 上的“java.lang.Exception:未找到 Web 浏览器”