Why can't you use dot notation when accessing information from CSV row object?

269 views Asked by At

I am trying to loop through a CSV file and print out information from the rows. I have two columns with headers "description" and "status". If I loop through the CSV file, I get a series of <CSV::Row "description":<description> "status":<status> objects. I can access the info by using csv_row["description"], but not csv_row.description. Since Ruby is creating objects out of the information on each line, why isn't it accessible with dot notation?

Sample code:

CSV.foreach(@file.path, headers:true) do |task|
    check_box = task["status"] == 0 ? "[ ] " : "[X] "
    puts check_box + task["description"]
end
1

There are 1 answers

0
Stefan On

CSV doesn't work that way but you could use OpenStruct:

require 'ostruct'

CSV.foreach(@file.path, headers: true) do |row|
  task = OpenStruct.new(row.to_hash)
  check_box = task.status == '0' ? '[ ]' : '[X]'
  puts "#{check_box} #{task.description}"
end

Or just create a custom class that fits your needs, e.g. via Struct:

Task = Struct.new(:status, :description) do
  def checkbox
    status == 0 ? '[ ]' : '[X]'
  end

  def to_s
    "#{checkbox} #{description}"
  end
end

CSV_OPTIONS = { headers: true, header_converters: :symbol, converters: :numeric }
CSV.foreach(@file.path, CSV_OPTIONS) do |row|
  task = Task.new(row[:status], row[:description])
  puts task
end