marcamillion marcamillion - 1 month ago 8
Ruby Question

How do I access the filename of the CSV file I just opened?

I have a method that looks like this:

def extract_websites
websites = []
csvs = Dir["#{@dir_name}/#{@state}/*.csv"]

csvs.each do |csv|
CSV.foreach(csv, headers: true) do |row|
websites << row['Website']
end
end
websites.uniq!
end


But what I need want to do is for each CSV file that is opened, I would like to detect the name of that file.

How do I do that?

Answer

In your sample the variable csv holds the path of the csv file. That local variable is available in the blocks of it's children, it shares it's scope down but not upwards. So

def extract_websites
  websites = []
  csvs = Dir["#{@dir_name}/#{@state}/*.csv"]

  csvs.each do |csv|
    puts File.expand_path(csv) # show the full path for each csv file
    CSV.foreach(csv, headers: true) do |row|
      puts csv # shows unexpanded path for each row of a csv
      websites << row['Website']
    end
  end
  websites.uniq!
end

should print out the path for each csv file and for each row