How can I select the longest string from a Ruby array?

前端 未结 3 1359
[愿得一人]
[愿得一人] 2021-02-06 23:55

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

For example if I have:

\'one\',\'two         


        
相关标签:
3条回答
  • 2021-02-07 00:03
    arr.map(&:length).max     -
    
    0 讨论(0)
  • 2021-02-07 00:13

    You can also use:

    ['one','two','three','four','five'].inject { |f, s| f.length > s.length ? f : s }
    
    0 讨论(0)
  • 2021-02-07 00:18

    Just do as below using Enumerable#max_by :

    ar = ['one','two','three','four','five']
    ar.max_by(&:length) # => "three"
    
    0 讨论(0)
提交回复
热议问题