Elmor
Elmor

Reputation: 4895

Ruby finding element with max value in multidimensional array using max_by

I'm trying to implement max_by to find element with highest value in multidimensional array.
code as follows

ar = [[123,345,43,35,43,1],[456,123,43,35,43,1],[675,123,43,35,43,1],[123,123,43,35,43,321]]
x = ar.max_by { |a,b| a <=> b }
p "result #{x.inspect}"

And the output is " result [456, 123, 43, 35, 43, 1]" Can you please explain to me what's wrong with my code ?

Update 1
using max_by

ar  = [ {a:1},{a:2},{a:3}]
x = ar.max_by { |e| e[:a] }
p "result #{x.inspect}"

I've left this update as a reminder for myself of whoever may bump into similar problem

Upvotes: 2

Views: 2422

Answers (3)

Eki Eqbal
Eki Eqbal

Reputation: 6057

Well, if I'm not mistaken then you'll need to find the greatest values of each subarray and the results should be something like:

[345, 456, 675, 321] 

If that what are you looking for:

x = ar.map{|x| x.max}

Upvotes: 0

Stefan
Stefan

Reputation: 114208

max_by handles the comparison for you, just return the maximum value for one element:

ar.max_by { |a| a.max }
#=> [675, 123, 43, 35, 43, 1]

Or even shorter:

ar.max_by(&:max)
#=> [675, 123, 43, 35, 43, 1]

Upvotes: 3

Arup Rakshit
Arup Rakshit

Reputation: 118289

You need to do :

ar = [[123,345,43,35,43,1],[456,123,43,35,43,1],[675,123,43,35,43,1],[123,123,43,35,43,321]]
x = ar.max { |a,b| a.max <=> b.max }

With #max_by, you are passing each element array, and then |a, b|, actually doing parallel assignment on a and b. This is not what you want I trust. What I have given above is the way to do it.

Upvotes: 4

Related Questions