Jesus Diaz Jesus Diaz - 6 months ago 10
Ruby Question

Return array with the longest strings only

Im learning Ruby and I can't figure out this exercise, I need have true in all 3 tests, I need to iterate the code until the array returns only the longest ones only. I've read other similar questions, but can't really understand them. Thanks.

# Tests
p longest(['tres', 'pez', 'alerta', 'cuatro', 'tesla', 'tropas', 'siete']) == ["alerta", "cuatro", "tropas"]
p longest(['gato', 'perro', 'elefante', 'jirafa']) == ["elefante"]
p longest(['verde', 'rojo', 'negro', 'morado']) == ["morado"]

Answer

Okay, let's break it down...

First: find out how long the longest word is:

words = ['tres', 'pez', 'alerta', 'cuatro', 'tesla', 'tropas', 'siete']
words.map(&:length).max
#=> 6

Second select all words with that length:

words.select { |w| w.length == 6 }
#=> ["alerta", "cuatro", "tropas"]

Combine that to a method:

def longest(words)
  max_length = words.map(&:length).max
  words.select { |w| w.length == max_length }
end