Sort an array of numbers in Scientific Notation

I would like to sort an array of numbers (in scientific notation) from smallest to highest.

This is what I tried (in vain):

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"]
+4
source share
2 answers

A block is expected Enumerable#sort -1, 0or 1. Do you want Enumerable#sort_by:

s.sort_by { |n| BigDecimal.new(n) }
# => ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
+11
source

Another option is BigDecimal#<=>in sort:

s.sort { |x, y| BigDecimal(x) <=> BigDecimal(y) }
#=> ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
+2
source

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


All Articles