web-dev-qa-db-ja.com

Ruby配列から最も長い文字列を選択するにはどうすればよいですか?

ただし、上記の[重複した提案]は多次元配列用であり、私がここで提起しているより単純なケースを対象としていません。

たとえば、私が持っている場合:

'one','two','three','four','five'

threeは最長の文字列なので選択したい。私は試した:

['one','two','three','four','five'].select{|char_num| char_num.size.max} 

しかし Enumerable#max は正しい結果を返しません。

28
Michael Durrant

Enumerable#max_by

ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"
56
Arup Rakshit
arr.map(&:length).max     -
1
Johnson

次のものも使用できます。

['one','two','three','four','five'].inject { |f, s| f.length > s.length ? f : s }
0
wbucko