Skip to content

Instantly share code, notes, and snippets.

@jdkealy
Created August 25, 2011 20:13
Show Gist options
  • Save jdkealy/1171759 to your computer and use it in GitHub Desktop.
Save jdkealy/1171759 to your computer and use it in GitHub Desktop.
class Output <
Struct.new(:name, :price)
end
unless ARGV.length == 1
puts "Wrong number of Arguments"
puts "Usage: ruby #{File.basename(__FILE__)} InputFile.tsv"
exit
end
# get the input filename from the command line
input_file = ARGV[0]
# define an array to hold the Output records
arr = Array.new
#make header indices global
name_index = ""
price_index = ""
#open file
f = File.open(input_file, "r")
#loop through file
f.each_with_index { |line, i|
#get indeces on first line
if(i==0) then
headers = line.split("\t")
#strip newline character off last column
last_index = headers.length - 1
headers[last_index] = headers.last.strip
#get indexes
name_index = headers.index("Name")
price_index = headers.index("Price")
end
#skip first line and lines beginning with a hash
next if i == 0
if line[0] == "#"
words = line.split("\t")
puts "WARNING: #{words[name_index]} this line should be skipped #{words[price_index]}"
next
end
words = line.split("\t")
p = Output.new
p.name = words[name_index]
p.price = words[price_index].to_f
arr.push(p)
}
# sort the data by the price field
arr.sort! { |a,b| a.price <=> b.price }
# print out all the sorted records
arr.each { |p|
puts p.name + "\t" + p.price.to_s + "\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment