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
- 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 }
Top comments (0)