Skip to content

Instantly share code, notes, and snippets.

@Rojo
Created September 29, 2014 15:54
Show Gist options
  • Save Rojo/db9f9c33b21628c745a7 to your computer and use it in GitHub Desktop.
Save Rojo/db9f9c33b21628c745a7 to your computer and use it in GitHub Desktop.
Book Index Sort
# 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