Ruby中最长的单词

cle*_*lem 8 ruby inject enumerable

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

ste*_*lag 27

我会做

class Array
  def longest_word
    group_by(&:size).max.last
  end
end
Run Code Online (Sandbox Code Playgroud)


Dav*_*hme 6

Ruby有一个标准方法,用于返回列表中具有最大值的元素.

anArray.max{|a, b| a.length <=> b.length}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用max_by方法

anArray.max_by(&:length)
Run Code Online (Sandbox Code Playgroud)

获得具有最大长度的所有元素

max_length = anArray.max_by(&:length).length
all_with_max_length = anArray.find_all{|x| x.length = max_length}
Run Code Online (Sandbox Code Playgroud)

  • 两种方法只返回单个元素,而不是一些长度相等的字符串. (4认同)