4

I have code that sorts the way I want. By multiple fields. Cool. But now I realized that sometimes the elements could be nil.

Q1: Any idea how to manage to get nil values at the top of the search? And get rid of this error message :in "<=>": undefined method "<=>" for nil:NilClass (NoMethodError)

Q2: in the code below I sort by 3 elements can I somehow define to sort asc by e[2], decs by e[0] and asc by e[1]. I am sorting csv file and most of the fields will be text fields.

array_of_arrays = [[1,9,'a'],[2,2,'a'], [2,6,''], [1,3,'a'], [2,1,'']] #doesnt work
array_of_arrays = [[1,9,'a'],[2,2,'a'], [2,6,'b'], [1,3,'a'], [2,1,'b']] # works
array_of_arrays.each {|line| p line }
puts
array_of_arrays.sort_by {|e| [e[2], e[0], e[1]]} .each {|line| p line }
2
  • 1
    If you want the secondary sort to be "decs by e[0]," then you'll need to negate it: sort_by { |e| [e[2].to_s, -e[0], e[1]] }. Commented Feb 11, 2010 at 23:04
  • @Wayne Conrad: hey Wayne, why did you delete your answer???? It was such a great answer.Especially the sorting part. I was about to vote for it now ... and it's gone .... Commented Feb 12, 2010 at 2:43

1 Answer 1

6

I think you can put e[2].to_s in sort_by. Or if it still generating error, try this:

e[2].nil? ? '' : e[2]

or

e[2].nil? ? ' ' : e[2]

or

e[2].blank? ? ' ' : e[2]

Some of those shoud work ;)

Q2: if column is numeric, than you can add - sign before that column, so:

 array_of_arrays.sort_by {|e| [e[2].to_s, -e[0], e[1]]} .each {|line| p line }
Sign up to request clarification or add additional context in comments.

2 Comments

@klew: it looks so easy when one knows what he is doing... Thank you. e[2].to_s works smoothly
I added second answer. However I don't know how to inverse order of strings and other objects.

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.