8

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

6 回答 6

29

我会做

class Array
  def longest_word
    group_by(&:size).max.last
  end
end
于 2011-03-06T20:12:16.643 回答
7

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

anArray.max{|a, b| a.length <=> b.length}

或者你可以使用 max_by 方法

anArray.max_by(&:length)

获取所有最大长度的元素

max_length = anArray.max_by(&:length).length
all_with_max_length = anArray.find_all{|x| x.length = max_length}
于 2011-03-06T20:07:25.790 回答
4

这是一个使用inject(不适用于空数组):

words.inject(['']){|a,w|
  case w.length <=> a.last.length
  when -1
    a
  when 0
    a << w
  when 1
    [w]
  end
}

可以缩短为

words.inject(['']){|a,w|
  [a + [w], [w], a][w.length <=> a.last.length]
}

对于那些喜欢高尔夫的人。

于 2011-03-06T20:21:14.160 回答
2

两个班轮:

vc = ['asd','s','1234','1235'].sort{|a,b| b.size <=> a.size}
vc.delete_if{|a| a.size < vc.first.size} 


#Output
["1235", "1234"]

或者如果你想使用注入,这使用你的想法,但它更短。

test_array.inject{ |ret,word|
   ret = [ret] unless ret.kind_of?(Array)

   ret << word  if word.size == ret.first.size
   ret = [word] if word.size > ret.first.size
   ret
}
于 2011-03-06T20:09:24.450 回答
1
module Enumerable
  def longest_word
    (strings = map(&:to_s)).
      zip(strings.map(&:length)).
      inject([[''],0]) {|(wws, ll), (w, l)|
        case  l <=> ll
        when -1 then [wws, ll] 
        when  1 then [[w], l]
        else         [wws + [w], ll]
        end
      }.first
  end
end

这个方法只依赖于泛型Enumerable方法,没有什么Array特别的,因此我们可以将它拉到Enumerable模块中,在那里它也可以用于Sets 或Enumerators,而不仅仅是Arrays。

于 2011-03-06T20:10:35.377 回答
0

该解决方案使用注入方法来累积数组中最长的字符串,然后选择长度最大的字符串。

动物 = [“老鼠”、“猫”、“鸟”、“熊”、“驼鹿”]

动物.inject(Hash.new{|h,k| h[k] = []}) { |acc, e| acc[e.size] << e; acc }.sort.last[1]

这将返回: ["mouse", "mouse"]

于 2016-09-18T12:15:13.740 回答