0

I have a question about Ruby. What I want to do is first to sort my items ascending and then write them out to a CSV-file. Now, the problem is further complicated by the fact that I want to iterate over a lot of CSV-files. I found this thread and the answer looks fine, but I am not able to get more than the last line written to my output file.

How can I get the whole data sorted and written to different CSV-files?

My code:

require 'date'
require 'csv'

class Daily < 

  # Daily has a open
  Struct.new(:open)

  # a method to print out a csv record for the current Daily.

  def print_csv_record
    printf("%s,", open)
    printf("\n")
  end
end

#------#
# MAIN #
#------#

# This is where I iterate over my csv-files:
foobar = ['foo', 'bar']
foobar.each do |foobar|

# get the input filename from the command line
input_file = "#{foobar}.csv"

# define an array to hold the Daily records
arr = Array.new

# loop through each record in the csv file, adding
# each record to my array while overlooking the header.    
f = File.open(input_file, "r")
f.each_with_index { |row, i|
  next if i == 0
  words = row.split(',')
  p = Daily.new
  # do a little work here to convert my numbers
  p.open = words[1].to_f
  arr.push(p)
}

# sort the data by ascending opens
arr.sort! { |a,b| a.open <=> b.open }

# print out all the sorted records (just print to stdout)
arr.each { |p|
  CSV.open("#{foobar}_new.csv", "w") do |csv|
    csv << p.print_csv_record  
  end    
}
end

My input CSV-file:

Open
52.23
52.45
52.36
52.07
52.69
52.38
51.2
50.99
51.41
51.89
51.38
50.94
49.55
50.21
50.13
50.14
49.49
48.5
47.92

My output CSV-file:

47.92
Community
  • 1
  • 1
ljnissen
  • 139
  • 1
  • 12
  • After the line `foobar.each do |foobar|`, everything should be indented in 2 spaces, and then an extra `end` at the end. Whenever you do `something do |x|`, you're opening a block that doesn't end until `end` shows up in your code. I suspect this might be breaking your code. – Dave Yarwood Jun 30 '14 at 18:10
  • EDIT: Never mind, I just saw `end` at the end there. You should still indent to make blocks more visible, though. – Dave Yarwood Jun 30 '14 at 18:11
  • Understand. Point taken. – ljnissen Jun 30 '14 at 18:14

1 Answers1

1

You need to put the iteration inside the open CSV file:

CSV.open("#{foobar}_new.csv", "w") do |csv|
  arr.each { |p|
    csv << p.print_csv_record  
  }
end    
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93