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

4

36

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.

Hazy answered 16/3, 2014 at 15:13 Comment(7)
you have 356 votes in ruby tag, at the time of writingSheffield
@emaillenin what a totally uninteresting numberTabor
possible duplicate of Find longest string in a array?Runthrough
@Monk, if you still have your benchmark code, I'd be interested to know how b = ar.map(&:size); ar[b.index(b.max)] compares with ar.max_by(&:size).Slumber
@CarySwoveland Monk provided.. But then he deleted.. But I can see it still, you don't :-)Hellbender
No, I cannot see it, @Arup. You must have excellent vision, as I have 20/20.Slumber
@CarySwoveland Actually. I am really able to see it. after 5,000 rep, you can see deleted answer too.. So I am able to see it.Hellbender
H
76

Just do as below using Enumerable#max_by :

ar = ['one','two','three','four','five']
ar.max_by(&:length) # => "three"
Hellbender answered 16/3, 2014 at 15:14 Comment(1)
Can I use bytesize vs length judging by the tests it is faster?Runthrough
C
2
arr.map(&:length).max     -
Coffle answered 29/9, 2014 at 19:34 Comment(2)
Please consider expanding on your answer.Luralurch
@johnson did you understand the question what the OP asked?Hellbender
M
0

You can also use:

['one','two','three','four','five'].inject { |f, s| f.length > s.length ? f : s }
Microbe answered 20/12, 2015 at 14:1 Comment(0)
G
0

I came up with this idea :

x = ""
['one','two','three','four','five'].each do |word|
   if word.length >= x.length
      x = word
   end
end

puts x
Googins answered 28/8, 2021 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.