Array of sort_by array with nil (ruby) elements

I have a code that sorts what I want. For several fields. Cool. But now I realized that sometimes the elements can be zero.

Q1: Any idea how to get null 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, I can somehow determine the sorting of asc by e [2], decs by e [0] and asc by e [1]. I will sort the 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 } 
+4
source share
1 answer

I think you can put e[2].to_s in sort_by . Or, if it still generates an error, try the following:

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

or

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

or

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

Some of these shoud work;)

Q2 : if the column is numeric, you can add a character - before this column, therefore:

  array_of_arrays.sort_by {|e| [e[2].to_s, -e[0], e[1]]} .each {|line| p line } 
+6
source

Source: https://habr.com/ru/post/1301054/


All Articles