Class: Sorter

Inherits:
Object
  • Object
show all
Defined in:
lib/sorter.rb

Instance Method Summary collapse

Constructor Details

#initializeSorter

Returns a new instance of Sorter.



3
4
5
6
7
8
9
# File 'lib/sorter.rb', line 3

def initialize
  @input_filename     = ENV["input_filename"]
  @sorted_filename    = ENV["sorted_filename"]
  @sort_column        = ENV["sort_column"].to_i
  @sort_as_int        = ENV["sort_as_int"] == "true"
  @column_separator   = ENV["column_separator"]
end

Instance Method Details

#sort!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/sorter.rb', line 11

def sort!
  lines = []
  infile = File.open(@input_filename)
  while line = infile.gets
    col = line.split(@column_separator, @sort_column + 2)[@sort_column]
    col = col.to_i if @sort_as_int
    lines << [col, line]
  end
  infile.close
  lines.sort!{ |a, b| a[0] <=> b[0] }
  outfile = File.open(@sorted_filename, "w")
  lines.each{ |line| outfile.print line[1] }
  outfile.close
end