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:)