1

From this question (@mudasobwa);

input.sort_by { |h| sorter.index(h[:id]) }

In some unfortunate cases; sorter.index(h[:id]) returns nil, it then returns an error

How would one cleanly avoid such error to happen, while having the rest of the array sorted ?

7
  • 1
    Add || -1 if you want them at the start or || sorter.size if you want them at the end. Commented Mar 7, 2018 at 11:23
  • Or better add || -Float::INFINITY. Commented Mar 7, 2018 at 11:24
  • what does || -Float::INFINITY would do compared to the two others ? adds it at the beginning ? Commented Mar 7, 2018 at 11:25
  • -Float::INFINITY will do the same as -1. You can put it as an alternative to the index. Aka sorter.index(h[:id]) || -Float::INFINITY. Commented Mar 7, 2018 at 11:25
  • ok thx a lot guys Commented Mar 7, 2018 at 11:27

1 Answer 1

1
input.sort_by { |h| [sorter.index(h[:id]) ? 1 : 0, sorter.index(h[:id])] }

This will take all values, sort them by whether they have a sorter.index(h[:id]) available initially, and then sort those with that value by that value

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.