From: Robert Klemme Date: 2007-07-19T21:32:15+09:00 Subject: Re: array sort_by with nil elements 2007/7/19, Stefan Rusterholz : > Josselin wrote: > > I am using the sort_by command > > > > @buddies = @user.buddies.compact.sort_by {|item| item.send @criteria} > > > > > > problem arise when one criteria like the user.name is nil the sort > > crash.... anyway to avoid it > > > > thanks a lot for your lights > > > > joss > > Simply add a default value (best one that gets sorted in the beginning > or the end) > @buddies = @user.buddies.compact.sort_by {|item| item.send(@criteria) || > default } This does not work. irb(main):003:0> [nil].sort_by {|it| it.send(:length) || 0} NoMethodError: undefined method `length' for nil:NilClass from (irb):3:in `send' from (irb):3 from (irb):3:in `sort_by' from (irb):3:in `each' from (irb):3:in `sort_by' from (irb):3 from :0 You actually need to deal with the exception or test beforehand that the item responds to the method. Kind regards robert