如何从Ruby数组中选择最长的字符串?

时间:2021-09-01 14:12:12

However above [duplicate suggestion] is for multidimensional array, not targeting the simpler case I am posing here.

但是上面的[重复建议]是多维数组,而不是针对我在这里提出的更简单的情况。

For example if I have:

例如,如果我有:

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

I want to select three as it is the longest string. I tried:

我想选择三个,因为它是最长的字符串。我试过了:

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

but Enumerable#max doesn't return the right result.

但是Enumerable #max不会返回正确的结果。

3 个解决方案

#1


43  

Just do as below using Enumerable#max_by :

使用Enumerable#max_by执行以下操作:

ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"

#2


1  

arr.map(&:length).max     -

#3


0  

You can also use:

您还可以使用:

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

#1


43  

Just do as below using Enumerable#max_by :

使用Enumerable#max_by执行以下操作:

ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"

#2


1  

arr.map(&:length).max     -

#3


0  

You can also use:

您还可以使用:

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