配列内の最長の単語を見つけるためにこのメソッドを作成しましたが、それを行うためのより良い方法があるかどうか疑問に思っています。私は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