Categories
ruby

Numerical sorting in ruby

Quick note on how to do numerical sorting in ruby.
When calling sort, ruby will perform a lexicographical sorting by default, meaning that the following array

a=["0","10","9","1"]
a.sort.each{|val| p val}

will output

"0"
"1"
"10"
"9"

If this is not what you want, this might be it:

a.sort{|x,y| x.to_i < => y.to_i}.each { |val| p val }

outputs:

"0"
"1"
"9"
"10"

Yay, blocks to the rescue:)

2 replies on “Numerical sorting in ruby”

Hi,

This probably isn’t that relevant, because this blog was posted three years ago, and you probably already know this, but you could also do this by using Enuermal#sort_by, as in:

a.sort_by { |n| n.to_i }

– Justin

Of course. That is by far a more elegant solution for this specific case. Don’t know what I was thinking at the time 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.