类似标题中的内容。我想用Ruby检索单词及其字符数。我搜索了很多,有很多方法可以选择数组中的元素。但是,例如,是否可以仅恢复数组中包含5个字符的字符串?
提前谢谢!
当然,这样的东西可以在中工作
words_with_five_characters = words.select { |w| w.length == 5 }
我假设您已经将标题转换为单词的array
,在这种情况下,@Ursus的答案是完美的。
如果这有任何帮助,您也可以直接从string
开始,并将scan
与正则表达式一起使用来识别5个字母的单词:
title = 'this is my title and it has a lot of words including some longer than five characters'
title.scan(/bw{5}b/)
=> ["title", "words"]