Skip to content

Instantly share code, notes, and snippets.

@davidx
Created October 30, 2009 22:20
Show Gist options
  • Save davidx/222775 to your computer and use it in GitHub Desktop.
Save davidx/222775 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
#
# In your favorite programming language, write a program to read a multiple line text file and write the
# N longest lines to a new file. Where N and the file to be read are specified on the command line.
require 'rubygems'
require 'choice'
Choice.options do
header ''
header 'Specific options:'
option :input_file_name, :required => true do
short '-f'
long '--file=FILE'
desc 'The file containing the lines'
end
option :output_file_name, :required => true do
short '-o'
long '--output=FILE'
desc 'The output file'
end
option :line_count, :required => true do
short '-c'
long '--count=COUNT'
desc 'The amount of lines to save'
end
separator ''
separator 'Common options: '
option :help do
long '--help'
desc 'Show this message'
end
end
input_file_name = Choice.choices[:input_file_name]
output_file_name = Choice.choices[:output_file_name]
line_count = Choice.choices[:line_count]
data = {}
lines = IO.read(input_file_name).split(/\n/)
lines.each do |line|
data[line.length] ? data[line.length].push(line) : data[line.length] = [line]
end
output_file_contents = data.sort.reverse.collect{|key,value| value }.flatten.slice(0,line_count.to_i).join("\n")
File.open(output_file_name, "w+") do |f|
f.syswrite(output_file_contents)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment