我希望能够从字符串中获取 3 个最长的单词。有没有一种巧妙的方法可以做到这一点而无需进入数组等?
问问题
886 次
3 回答
9
>> str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'
>> str.split.map { |s| s.gsub(/\W/, '') }.sort_by(&:length)[-3..-1]
=> ["adipisicing", "consectetur", "exercitation"]
于 2012-05-07T13:07:42.743 回答
1
"some string with words that are of different length".split(/ /).sort_by(&:length).reverse[0..2]
于 2012-05-07T13:09:26.500 回答
1
从 Ruby 2.2 开始, Enumerable 、max_by
和采用可选参数,允许您指定将返回多少个元素。min_by
max
min
str.scan(/[[:alnum:]]+/).max_by(3, &:size)
# => ["exercitation", "consectetur", "adipisicing"]
于 2015-05-11T13:49:28.660 回答