How to sort an array of floats in Ruby?

Just wondering how to sort a float array in Ruby, since "sort" and "sort!" only work for whole arrays.

+4
source share
3 answers

Arrays of floats can certainly be sorted:

>> [6.2, 5.8, 1.1, 4.9, 13.4].sort => [1.1, 4.9, 5.8, 6.2, 13.4] 

Perhaps you have nil in your array that cannot be sorted with anything.

+7
source

You can sort a floating-point array without any problems, for example:

 irb(main):005:0> b = [2.0, 3.0, 1.0, 4.0] => [2.0, 3.0, 1.0, 4.0] irb(main):006:0> b.sort => [1.0, 2.0, 3.0, 4.0] 
+4
source

perhaps you have something like this in your array and have not noticed:

 [1.0 , 3.0, 0/0, ...] 

the 0/0 will give you a NaN that cannot be compared to Float ... in which case you should try

 [2.3,nil,1].compact.sort # => [1,2.3] 

that or perhaps the same error with 1.0/0 that gives infinity (but this error is detected by ruby)

+4
source

Source: https://habr.com/ru/post/1345616/


All Articles