Ruby longest word in array Ruby longest word in array ruby ruby

Ruby longest word in array


I would do

class Array  def longest_word    group_by(&:size).max.last  endend


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).lengthall_with_max_length = anArray.find_all{|x| x.length = max_length}


Here's one using inject (doesn't 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 shortened to

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

for those who like golf.