以科学计数法对数字数组进行排序
Sort array of numbers in Scientific Notation
我想对一组数字(以科学记数法)从小到大进行排序。
这是我尝试过的方法(徒劳无功):
require 'bigdecimal'
s = ['1.8e-101','1.3e-116', '0', '1.5e-5']
s.sort { |n| BigDecimal.new(n) }.reverse
# Results Obtained
# => [ "1.3e-116", "1.8e-101", "0", "1.5e-5" ]
# Expected Results
# => [ "0", "1.3e-116", "1.8e-101", "1.5e-5"]
Enumerable#sort
的块预计 return -1
、0
或 1
。你要的是Enumerable#sort_by
:
s.sort_by { |n| BigDecimal.new(n) }
# => ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
另一种选择是在 sort
:
中使用 BigDecimal#<=>
s.sort { |x, y| BigDecimal(x) <=> BigDecimal(y) }
#=> ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
我想对一组数字(以科学记数法)从小到大进行排序。
这是我尝试过的方法(徒劳无功):
require 'bigdecimal'
s = ['1.8e-101','1.3e-116', '0', '1.5e-5']
s.sort { |n| BigDecimal.new(n) }.reverse
# Results Obtained
# => [ "1.3e-116", "1.8e-101", "0", "1.5e-5" ]
# Expected Results
# => [ "0", "1.3e-116", "1.8e-101", "1.5e-5"]
Enumerable#sort
的块预计 return -1
、0
或 1
。你要的是Enumerable#sort_by
:
s.sort_by { |n| BigDecimal.new(n) }
# => ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
另一种选择是在 sort
:
BigDecimal#<=>
s.sort { |x, y| BigDecimal(x) <=> BigDecimal(y) }
#=> ["0", "1.3e-116", "1.8e-101", "1.5e-5"]