The longest Ruby word in an array

I built this method to find the longest word in an array, but I'm wondering if there is a better way to do this. I am new to Ruby and just did it as an exercise to learn the inject method.

It returns either the longest word in the array or an array of the 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 
+8
ruby inject enumerable
source share
6 answers

I would do

 class Array def longest_word group_by(&:size).max.last end end 
+27
source share

Ruby has a standard method for returning an item to a list with a maximum value.

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

or you can use max_by method

 anArray.max_by(&:length) 

to get all items with maximum length

 max_length = anArray.max_by(&:length).length all_with_max_length = anArray.find_all{|x| x.length = max_length} 
+6
source share

Here inject used (does not work for an empty array):

 words.inject(['']){|a,w| case w.length <=> a.last.length when -1 a when 0 a << w when 1 [w] end } 

which can be reduced to

 words.inject(['']){|a,w| [a + [w], [w], a][w.length <=> a.last.length] } 

for those who love golf.

+4
source share

Two liners:

 vc = ['asd','s','1234','1235'].sort{|a,b| b.size <=> a.size} vc.delete_if{|a| a.size < vc.first.size} #Output ["1235", "1234"] 

or if you want to use an injection, use this idea, but its shorter one.

 test_array.inject{ |ret,word| ret = [ret] unless ret.kind_of?(Array) ret << word if word.size == ret.first.size ret = [word] if word.size > ret.first.size ret } 
+1
source share
 module Enumerable def longest_word (strings = map(&:to_s)). zip(strings.map(&:length)). inject([[''],0]) {|(wws, ll), (w, l)| case l <=> ll when -1 then [wws, ll] when 1 then [[w], l] else [wws + [w], ll] end }.first end end 

This method depends only on the general Enumerable methods, there is nothing special about Array , so we can pull it into the Enumerable module, where it will also be available for Set or Enumerator s, and not just Array s.

+1
source share

This solution uses the injection method to accumulate the longest lines in the array, and then those that have the longest are selected.

animals = ["mouse", "cat", "bird", "bear", "moose"]

animals.inject (Hash.new {| h, k | h [k] = []}) {| acc, e | acc [e.size] <e; acc} .sort.last [1]

This returns: ["mouse", "mouse"]

0
source share

All Articles