Matthew Henry John Bartlett

+64 27 211 3455
email me

Thursday 18 April, 02013

Ruby code to combine ranges in a book index

by Matthew Bartlett @ 9:51 pm
def combine_nums(line)
line.gsub!(/(\d+), (?=(\d+))/) { # combine consecutive & identical numbers
if $2.to_i - $1.to_i == 1 # (looks-ahead so as to check
"#{$1}-" # every set of two numbers)
elsif $2.to_i == $1.to_i
""
else
"#{$1}, "
end
}
line.gsub!(/-(\d+), (\d+)/) { # remove numbers after ranges included in same
if $2.to_i < $1.to_i
"-#{$1}"
else
"#{$&}"
end
}
line.gsub!(/(\d+)-(\d+-)+(\d+)/) { "#{$1}-#{$3}" } # remove inner numbers from ranges
line.gsub!(/(\d)(\d\d)-\1(\d\d)/) { "#{$1}#{$2}-#{$3}"} # make e.g. 323-343 into 323-43
line.gsub!(/(\d0\d)-0(\d)/) { "#{$1}-#{$2}"} # make e.g. 306-08 into 306-8
return line
end
if ARGV.empty?
puts "Please supply a filename, or --clipboard"
elsif ARGV[0] == "--clipboard"
require 'clipboard'
clipout = []
Clipboard.paste.split("\r").each { |line| clipout << combine_nums(line) }
Clipboard.copy(clipout.join("\r"))
else
File.open(ARGV[0]).each(sep="\r") do |line| # Mac classic newlines
puts combine_nums(line)
end
end
view raw gistfile1.txt hosted with ❤ by GitHub

Leave a Reply