我怎样才能选择一个Ruby数组中最长的字符串? [英] How can I select the longest string from a Ruby array?
本文介绍了我怎样才能选择一个Ruby数组中最长的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不过上述[重复建议]是多维数组,不是针对我在这里提出这个简单的案例。
However above [duplicate suggestion] is for multidimensional array, not targeting the simpler case I am posing here.
例如,如果我有:
'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}
但可枚举#最大不返回正确的结果
推荐答案
只是做如下使用<一个href=\"http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-max_by\"><$c$c>Enumerable#max_by$c$c>
Just do as below using Enumerable#max_by
:
ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"
这篇关于我怎样才能选择一个Ruby数组中最长的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文