Find the longest word (in Ruby)

Polina Marchenko
2 min readFeb 15, 2017

--

The next task is to write a method which returns the longest word in a string.

# Write a method that takes in a string. Return the longest word in
# the string. You may assume that the string contains only letters and
# spaces.
#
# You may use the String `split` method to aid you in your quest.

I could recall the .sort! method which sorts the the words in a string. Per default .sort! sorts from the shortest word to the longest one. So in our case we needed to find the longest word. I did not know immediately how exactly to apply the method, so the research on StockOverflow helped.

In fact there are several options available.

  1. Using .split, .sort_by! and .reverse! method. .split — converts string into an array, in our case we assume that the string parameter ‘sentence’ will take an argument which consists of several words that’s why we use .split(“ “) with a white space between parentheses. .sort_by! — allows us to decide what to sort on, i.e. length. Because sort_by! sorts the array per default from the shortest to the longest we need to reverse the order using .reverse! method. (&:length) syntax was new to me, I knew an alternative way of writing the same as:
longest.sort_by!{|word| word.length}

I find the (&:length) more elegant and have used it:

def longest_word(sentence)
longest = sentence.split(“ “) #convert a string into an array
longest.sort_by!(&:length).reverse!
#sort by the length and start with the longest one
longest[0] #return the first item of the array (with 0 index)
end
longest_word(“Polina loves chocolate”)
#output would be
#=> "chocolate"

2. Second alternative is using .split, .sort! and <=> (the spaceship operator). Again we are using .split to convert string into an array. Then we use .sort! method to sort the items in the array. The spaceship operator can be used to control how the items are compared.

longest.sort!{|a, b| a.length <=> b.length} 
#if you sort from the shortest to the longest
longest.sort!{|a, b| b.length <=> a.length}
#if you want to sort backwards

Important: when you want to use the spaceship operator, it needs two items passed into the block! These two items need to be compared right now. It does not mean that your array can have only two items. In this case we do not need the reverse! method any more and can even write all operations in one line.

def longest_word(words) 
words.split(" ").sort! {|a_word, b_word| b_word.length <=> a_word.length}[0]
end
longest_word("Polina loves vanilla too")
#output would be
#=> "vanilla"

If my explanations are not clear enough, please check this Stack Overflow thread, a really great one.

--

--

Polina Marchenko

Mom. Geekette, Entrepreneur, Product Manager. Passionate about edtech, behavior design, community building, and human brain.