DEV Community

DAI
DAI

Posted on

sorting an array that contains nil in Ruby using sort_by

Hi, I'm CEO at Indieverse and owner of DAINOTE

Premise

  • If there is an array like the following, trying to sort it can sometimes fail
arr = [1,2,3,4,5,nil,6,7,8]
arr.sort_by{|item| item}
# -> ArgumentError: comparison of Integer with nil failed
Enter fullscreen mode Exit fullscreen mode
  • When nil is present, I want to consider the nil value and change it to the oldest value before sorting

Conclusion

  • Treat nil as Float::INFINITY (infinity)

ruby
arr = [1,2,3,4,5,nil,6,7,8]
arr.sort_by { |item| item.nil? ? Float::INFINITY : item }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)