Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I tried:

['one','two','three','four','five'].select{|char_num| char_num.size.max}  

but Enumerable#max doesn't return the right result.

like image 525
Michael Durrant Avatar asked Mar 16 '14 15:03

Michael Durrant


People also ask

How do you find the largest number in an array in Ruby?

The array. max() method in Ruby enables us to find the maximum value among elements of an array. It returns the element with the maximum value.

What does .length do in Ruby?

length is a String class method in Ruby which is used to find the character length of the given string. Returns:It will return the character length of the str.


2 Answers

Just do as below using Enumerable#max_by :

ar = ['one','two','three','four','five'] ar.max_by(&:length) # => "three" 
like image 191
Arup Rakshit Avatar answered Sep 21 '22 07:09

Arup Rakshit


arr.map(&:length).max     - 
like image 35
Johnson Avatar answered Sep 21 '22 07:09

Johnson