开发者

Longest item in array

Is there an easier way than below to find the longest item in an array开发者_Go百科?

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]


Edit: The former versions were a little wrong and unclear concerning the version numbers

Starting with Ruby versions 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 that object which has had the largest result.

In simple cases like this, where the block only consists of one method name and some variable noise, there is actually no need for an explicit block. It is possible make use of the Symbol#to_proc method and avoid the block variable altogether, making this:

@rows = arr.max_by(&:length)

Earlier versions of Ruby lack both the #to_proc and the #max_by method. 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.


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


You could sort the array based on length and then pull the longest.

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

Not really that efficient, but it's an alternative. If you didn't want to use a new array and didn't care about the ordering in the @rows array you could just use the sort! method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜