0
  def csv_parsing
    require 'csv'
    csv_file_path = File.join(File.dirname(__FILE__), "csv_data.csv")
    CSV.parse(csv_file_path) do |line|
      puts line[0]
    end
  end

This is a simple example, how I try to parse CSV file. The action above is placed in controller, the file is in the project's root.

But instead of getting the data from CSV file I am getting the path to file, like:

/Users/my_mane/ruby_folder/my_project/app/controllers/csv_data.csv

Note: the file contain a real data.

Why is printed out instead of own data just the file path?

user984621
  • 46,344
  • 73
  • 224
  • 412

2 Answers2

2

Because CSV#parse actually parses the string you passed to it, not the file from location that this string contains. What you need is CSV#read: http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-read

Anton
  • 3,006
  • 3
  • 26
  • 37
1

If you use file path and not data in string, then you can read this file line by line with:

CSV.foreach(csv_file_path) do |line|
  ...
end
bender
  • 1,430
  • 10
  • 14