Ruby Quick Reference

Quick reference for efficient coding

View the Project on GitHub YumaYX/RubyQuickReference

read_with_new.rb(csv)

This Ruby code reads a CSV file named “file.csv” and prints each row as an array of header-value pairs. It utilizes the CSV library to handle the parsing of the CSV file and iterates through each row, printing the header and corresponding value for each column in that row.

Execution:

require 'csv'
#=> true

File.open("file.csv", "r") do |f|
  csv = CSV.new(f, headers: true)
  csv.each do |line|
      line.each do |header, val|
          p [header, val]
      end
      puts
  end
end
["key", "key1"]
["value", "value1"]

["key", "key2"]
["value", "value2"]

["key", "key3"]
["value", "value3"]

#=> nil

Executed with Ruby 3.3.5