Philip
Philip

Reputation: 7166

Ruby - Find the top 3 longest words in a string

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

Answers (3)

steenslag
steenslag

Reputation: 80065

Since Ruby 2.2 Enumerable max_by, min_by,maxand 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

Jakob W
Jakob W

Reputation: 3377

"some string with words that are of different length".split(/ /).sort_by(&:length).reverse[0..2]

Upvotes: 1

Christopher Creutzig
Christopher Creutzig

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

Related Questions