Jesus Diaz Jesus Diaz - 4 months ago 6
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"]


Okay, let's break it down...

First: find out how long the longest word is:

words = ['tres', 'pez', 'alerta', 'cuatro', 'tesla', 'tropas', 'siete']
#=> 6

Second select all words with that length: { |w| w.length == 6 }
#=> ["alerta", "cuatro", "tropas"]

Combine that to a method:

def longest(words)
  max_length = { |w| w.length == max_length }