Reputation: 7166
I want to be able to get the 3 longest words from a string. Is there a neat way of doing this without getting into arrays etc?
Upvotes: 1
Views: 925
Reputation: 80065
Since Ruby 2.2 Enumerable max_by
, min_by
,max
and min
take an optional argument, allowing you to specify how many elements will be returned.
str.scan(/[[:alnum:]]+/).max_by(3, &:size)
# => ["exercitation", "consectetur", "adipisicing"]
Upvotes: 1
Reputation: 3377
"some string with words that are of different length".split(/ /).sort_by(&:length).reverse[0..2]
Upvotes: 1
Reputation: 8774
>> 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"]
Upvotes: 9