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.
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.
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.
Just do as below using Enumerable#max_by
:
ar = ['one','two','three','four','five'] ar.max_by(&:length) # => "three"
arr.map(&:length).max -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With