Я создал этот метод для поиска самого длинного слова в массиве, но мне интересно, есть ли лучший способ получить сделал это. Я новичок в Ruby и просто сделал это как упражнение для изучения метода inject
.
Он возвращает либо самое длинное слово в массиве, либо массив одинаковых самых длинных слов.
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