Created
September 29, 2014 15:54
-
-
Save Rojo/db9f9c33b21628c745a7 to your computer and use it in GitHub Desktop.
Book Index Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sorts an array of decimals as if the were the chapters and sections of a book | |
sections = [3.1, 3.11, 3.2, 3.3, 3.8, 3.7 , 3.8, 3.9, 3.10] | |
sections.sort do |e1, e2| | |
if e1.to_i == e2.to_i # Comparing sections within the same chapter | |
# Get the real value for the section within the chapter | |
n1 = e1 + e1.to_s.split('.')[1].to_i | |
n2 = e2 + e2.to_s.split('.')[1].to_i | |
# Compare using the real value of the section | |
n1 <=> n2 | |
else # Comparing different chapters | |
e1 <=> e2 | |
end | |
end | |
# => [3.1, 3.1, 3.2, 3.3, 3.7, 3.8, 3.8, 3.9, 3.11] | |
# As you can see, 3.10 is represented as if it was 3.1, so it may be better | |
# to store the sections as strings. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment