I've got a file that I read in the values from and place into an array so I can sort them:
input.txt
#75 - Hamilton Ave.
#12A - Long Road
#12B - Long Road
#120 - Curvy Road
My ruby:
result = []
file = open("input.txt").each do | line |
result << line
end
puts result.sort_by {|x| x.to_i}.reverse
I want to sort by the integer value in the string. However the order comes out as:
#12A - Long Road
#12B - Long Road
#120 - Curvy Road
#75 - Hamilton Ave.
Instead of:
#12A - Long Road
#12B - Long Road
#75 - Hamilton Ave.
#120 - Curvy Road
Should I be using some sort of regex to eval the string when sorting?
"# 123anything"will always be zero.result.sort_by {|x| x[1..-1].to_i}.reverse. For example"#74 - Hamilton Ave."[1..-1] #=> "74 - Hamilton Ave.".result.sort_by {|x| [x[1..-1].to_i,x]}so the full string can be used as the tie breaker.reversel. By the time I noticed those two things Mr. Jordan had posted his solution.