dugq
dugq

Reputation: 63

sorting multidimension array on secondary element where primary element is nil

I have a multidimensional array where each array element in the primary array has two sub-elements and the second sub-element can sometimes be nil. I want to sort the primary array on the second sub-element, unless the second sub-element is nil, in which case I want the sort to look to the first sub-element for purposes of figuring out the order.

So, this data

[[7, nil], [5, 4], [3,9]]

would be sorted like this

[[5, 4], [7, nil], [3,9]]

Is there a way to do this?

Thanks!

Upvotes: 1

Views: 60

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

1.8.7 > [[7, nil], [5, 4], [3,9]].sort_by{|a| a.last.nil? ? a.first : a.last}
 => [[5, 4], [7, nil], [3, 9]] 

Upvotes: 3

Related Questions