然而,上面的重复建议是针对多维数组的,而不是针对我在这里提出的更简单的情况。
例如,如果我有:
'one','two','three','four','five'
我想选择three
,因为它是最长的字符串。我试过了:
['one','two','three','four','five'].select{|char_num| char_num.size.max}
但是Enumerable#max没有返回正确的结果。
发布于 2014-03-16 23:14:01
只需使用Enumerable#max_by
执行以下操作:
ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"
发布于 2014-09-30 03:34:54
arr.map(&:length).max -
发布于 2015-12-20 22:01:00
您还可以使用:
['one','two','three','four','five'].inject { |f, s| f.length > s.length ? f : s }
https://stackoverflow.com/questions/22438646
复制相似问题