[英]How can I select the longest string from a Ruby array?
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. 我想选择
three
因为它是最长的字符串。 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不能返回正确的结果。
Just do as below using Enumerable#max_by
: 只需使用
Enumerable#max_by
以下操作:
ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"
arr.map(&:length).max -
您还可以使用:
['one','two','three','four','five'].inject { |f, s| f.length > s.length ? f : s }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.