Answer the question
In order to leave comments, you need to log in
How to properly sort an array without errors?
There is such a code. In which I sort the array by the name of the objects.
array.sort_by do |item|
if item.expression
[item.title, item.description]
else
[item.first_name, item.last_name]
end
end
Answer the question
In order to leave comments, you need to log in
No way. An error will interrupt your sorting at the most interesting place. Therefore, the error should not be processed, but prevented. First you need to make a responsible decision: where should the nameless elements go - up or down? And then come up with default key values for them and rewrite the code block inside sort_by so that they are substituted if necessary.
Once again, to consolidate: if an error is thrown, sorting is interrupted (after all, you do not have your own error handler inside the sorting algorithm, because you did not write it). Therefore, it is correct and understandable to handle the error in any way.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question