Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby longest word in array

I built this method to find the longest word in an array, but I'm wondering if there's a better way to have done it. I'm pretty new to Ruby, and just did this as an exercise for learning the inject method.

It returns either the longest word in an array, or an array of the equal longest words.

class Array
  def longest_word
    # Convert array elements to strings in the event that they're not.
    test_array = self.collect { |e| e.to_s }
    test_array.inject() do |word, comparison|
      if word.kind_of?(Array) then
        if word[0].length == comparison.length then
          word << comparison
        else
          word[0].length > comparison.length ? word : comparison
        end
      else
        # If words are equal, they are pushed into an array
        if word.length == comparison.length then
          the_words = Array.new
          the_words << word
          the_words << comparison
        else
          word.length > comparison.length ? word : comparison
        end
      end
    end
  end
end
like image 333
clem Avatar asked Mar 06 '11 19:03

clem


People also ask

How do you find the longest word in an array?

Find the Longest Word With the sort() Method For this solution, we will use the Array. prototype. sort() method to sort the array by some ordering criterion and then return the length of the first element of this array. The sort() method sorts the elements of an array in place and returns the array.

What does .length do in Ruby?

length is a String class method in Ruby which is used to find the character length of the given string. Returns:It will return the character length of the str.


2 Answers

I would do

class Array
  def longest_word
    group_by(&:size).max.last
  end
end
like image 127
steenslag Avatar answered Oct 01 '22 00:10

steenslag


Ruby has a standard method for returning an element in a list with the maximum of a value.

anArray.max{|a, b| a.length <=> b.length}

or you can use the max_by method

anArray.max_by(&:length)

to get all the elements with the maximum length

max_length = anArray.max_by(&:length).length
all_with_max_length = anArray.find_all{|x| x.length = max_length}
like image 38
David Nehme Avatar answered Oct 01 '22 00:10

David Nehme