Skip to content

Instantly share code, notes, and snippets.

@pedroreys
Created September 21, 2011 02:24
Show Gist options
  • Save pedroreys/1231052 to your computer and use it in GitHub Desktop.
Save pedroreys/1231052 to your computer and use it in GitHub Desktop.
csv manipulation test
#!/usr/bin/env ruby
# I have a csv file with some students scores. The data in the file looks like:
# Last Name,First Name,EID,Special Codes,Score,Percent
# DOE ,JOHN ,JHD123,,92,92
# ...
# Total Records Read,352,,,,
# I need to add a specific value to the last two columns in each data row.
# As I'm learning ruby I decided to write a ruby script to do that instead of using C# or Powershell.
# Is there a better way of doing this?
require 'csv'
require 'choice'
Choice.options do
header ''
header 'Specify options:'
option :source, :required => true do
short '-s'
long '--source=SOURCE'
desc 'the csv file with the grades'
end
option :destination, :required => true do
short '-d'
long '--destination=DESTINATION'
desc 'the name of the new csv file to be generated with the curve value added'
end
option :curve, :required => true do
short '-c'
long '--curve=CURVE'
desc 'the curve value to be added to the scores'
cast Integer
end
end
@source_file = Choice.choices[:source]
@destination_file = Choice.choices[:destination]
@curve = Choice.choices[:curve]
def numeric?(object)
true if Float(object) rescue false
end
CSV.open(@destination_file, "wb") do |new_row|
CSV.foreach(@source_file) do |row|
if(numeric?(row[4]))
new_row << [row[0], row[1], row[2], row[3], row[4].to_i + @curve, row[5].to_i + @curve]
else
new_row << row
end
end
end
@jwo
Copy link

jwo commented Sep 22, 2011

If it works, there's nothing necessarily wrong with what you wrote here.

You may want to look at 'choices' to help with the command line input requirements... Also, if you add code like this, then you can tell if the file was executed in ruby, rather than just required.

if FILE == $0
puts "I was ran, not just required'
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment