davidx (owner)

Revisions

gist: 222775 Download_button fork
public
Public Clone URL: git://gist.github.com/222775.git
Embed All Files: show embed
nlines #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/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