19Nov/082
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
1 2 | 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:
1 | a.sort{|x,y| x.to_i < => y.to_i}.each { |val| p val } |
outputs:
"0" "1" "9" "10"
Yay, blocks to the rescue:)
June 30th, 2011 - 02:38
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
June 30th, 2011 - 10:32
Of course. That is by far a more elegant solution for this specific case. Don’t know what I was thinking at the time