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

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"]

または、injectを使用する場合は、アイデアを使用しますが、より短いです。

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プルアップして、sだけでなくsまたはsでも使用できるようにすることができます。EnumerableSetEnumeratorArray

于 2011-03-06T20:10:35.377 に答える
0

このソリューションでは、inject メソッドを使用して配列内の最長の文字列を蓄積し、最も長い文字列を選択します。

動物 = [「マウス」、「猫」、「鳥」、「クマ」、「ヘラジカ」]

Animals.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 に答える