Ruby sort by (integer) "comparing NilClass with 3200 failed"

I want to sort my entries in a rails application:

@ebms = Ebm.all @ebms.sort_by! {|u| u.number} 

u.number defined as an integer! The problem is that Rails cannot compare it to nil :

 comparison of NilClass with 32400 failed 

What can I do to avoid this error?

+7
sorting ruby ruby-on-rails
source share
2 answers

How to try to convert nil to integer?

  @ebms = Ebm.all @ebms.sort_by! { |u| u.number.to_i } 
+6
source share

You can add a default value for comparison, which will be used when number is nil:

 @ebms = Ebm.all @ebms.sort_by! {|u| u.number || 0} 

Or you can follow the recommendations in this answer to select those who have a number and sort them, and then add them without a number to the list.

+12
source share

All Articles