我建立了此方法来查找数组中最长的单词,但我想知道是否有更好的方法可以做到这一点。我是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

最佳答案

我会做

class Array
  def longest_word
    group_by(&:size).max.last
  end
end

关于Ruby数组中最长的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5212972/

10-12 00:30
查看更多