Just wondering how to sort an array of floats in Ruby, since "sort" and "sort!" only work for integer arrays.
只是想知道如何在Ruby中对浮点数组进行排序,因为“排序”和“排序!”仅适用于整数数组。
3 个解决方案
#1
7
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]
Maybe you have a nil
in your array, which can't be sorted with anything.
也许你的数组中有一个nil,不能用任何东西排序。
#2
4
You can sort a float array without any problem like :
你可以排序一个浮点数组没有任何问题,如:
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]
#3
4
perhaps you have something like this in your array and haven't noticed:
也许你的数组中有这样的东西并且没有注意到:
[1.0 , 3.0, 0/0, ...]
the 0/0
will give you a NaN
which is impossible to compare with a Float... in this case you should try to
0/0会给你一个NaN,这是不可能与Float比较...在这种情况下你应该尝试
[2.3,nil,1].compact.sort
# => [1,2.3]
that or perhaps the same error with 1.0/0
wich yields infinity (but this error is detected by ruby)
或者1.0 / 0的相同错误产生无穷大(但红宝石检测到此错误)
#1
7
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]
Maybe you have a nil
in your array, which can't be sorted with anything.
也许你的数组中有一个nil,不能用任何东西排序。
#2
4
You can sort a float array without any problem like :
你可以排序一个浮点数组没有任何问题,如:
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]
#3
4
perhaps you have something like this in your array and haven't noticed:
也许你的数组中有这样的东西并且没有注意到:
[1.0 , 3.0, 0/0, ...]
the 0/0
will give you a NaN
which is impossible to compare with a Float... in this case you should try to
0/0会给你一个NaN,这是不可能与Float比较...在这种情况下你应该尝试
[2.3,nil,1].compact.sort
# => [1,2.3]
that or perhaps the same error with 1.0/0
wich yields infinity (but this error is detected by ruby)
或者1.0 / 0的相同错误产生无穷大(但红宝石检测到此错误)