我构建了这个方法来查找数组中最长的单词,但我想知道是否有更好的方法来完成它。我对 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