I’m having a problem sorting an array. My expected result is:
@list = [
["2 1/8\"", "23 13/32\"", "stile", "2"],
["2 1/8\"", "11 5/32\"", "rail", "6"],
["2 1/8\"", "7 13/32\"", "stile", "4"]
]
This is just an example since the array is dynamic and data are always changing, but the one thing that is constant is that most if not all single digit measurements end up at the beginning.
And here’s the code I’m using:
@list = @list.sort {|a,b| b[1]<=>a[1]}
Here’s the actual output from the code.
@list
# => [
# ["2 1/8\"", "7 13/32\"", "stile", "2"],
# ["2 1/8\"", "23 13/32\"", "rail", "6"],
# ["2 1/8\"", "11 5/32\"", "stile", "4"]
# ]
Any ideas why?
If the goal is to sort by the first numeric value of the second value of each array (7, 23, 11) converting the string to integer in the sort could be a solution:
You can also make it shorter by using
sort!: