The longest element in the array

Is there an easier way than below to find the longest element in an array?

arr = [ [0,1,2], [0,1,2,3], [0,1,2,3,4], [0,1,2,3] ] longest_row = [] @rows.each { |row| longest_row = row if row.length > longest_row.length } p longest_row # => [0,1,2,3,4] 
+4
source share
3 answers

Edit: previous versions were slightly incorrect and unclear regarding version numbers

Starting with versions of Ruby 1.9 and 1.8.7+, the Enumerable#max_by method is available:

 @rows = arr.max_by{|a| a.length} 

max_by executes the given block for each object in arr and then returns the object that had the greatest result.

In simple cases like this, when a block consists of only one method name and some variable noise, there is really no need for an explicit block. You can use the Symbol#to_proc and completely exclude the block variable by doing this:

 @rows = arr.max_by(&:length) 

Earlier versions of Ruby lacked the #to_proc and #max_by . Therefore, we need to explicitly give our actual comparison and use Enumerable#max .

 @rows = arr.max{|c1, c2| c1.length <=> c2.length} 

Thanks to all comments for clarification.

+20
source

arr.inject {| long current | longest.length> current.length? longest: current}

+1
source

You can sort the array by length, and then stretch the longest.

 sorted_rows = @rows.sort{|x,y| y.length<=>x.length} longest_row = sorted_rows.first 

Not as effective, but it is an alternative. If you didn't want to use the new array and didn't care about ordering in the @rows array, you could just use sorting! Method.

0
source

Source: https://habr.com/ru/post/1309154/


All Articles