D
D
Demigodd2019-08-08 15:43:45
Ruby on Rails
Demigodd, 2019-08-08 15:43:45

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

But here's the trouble if, for example, instead of first_name or last_name there will be nil , false .
Those are mistakes. The error was: comparison of Array with Array failed. do not pass.
How in my case it is correct and clear to process an error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2019-08-08
@Demigodd

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 question

Ask a Question

731 491 924 answers to any question