1

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!

0

1 Answer 1

3
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]] 
Sign up to request clarification or add additional context in comments.

1 Comment

{ |a| a.last || a.first } would an option if the sub-arrays only contain numbers and nils.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.