Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of numbers in Scientific Notation

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

This is what I have 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"]
like image 395
Ismail Moghul Avatar asked Dec 11 '22 19:12

Ismail Moghul


2 Answers

The block of Enumerable#sort is expected to return -1, 0 or 1. What you want is Enumerable#sort_by:

s.sort_by { |n| BigDecimal.new(n) }
# => ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
like image 147
Yu Hao Avatar answered Jan 03 '23 20:01

Yu Hao


Another option is to use BigDecimal#<=> within sort:

s.sort { |x, y| BigDecimal(x) <=> BigDecimal(y) }
#=> ["0", "1.3e-116", "1.8e-101", "1.5e-5"]
like image 40
Stefan Avatar answered Jan 03 '23 19:01

Stefan