read a csv file in ruby

To read a CSV file in ruby, you can use the CSV class from the standard library. Here's an example code snippet:

main.rb
require 'csv'

# Use the `foreach` method to read the file line by line
CSV.foreach('my_data.csv') do |row|
  # Each `row` is an array of columns in the CSV file
  puts row.inspect
end

# Alternatively, you can read the whole file into memory using the `read` method
csv_data = CSV.read('my_data.csv')

# `csv_data` is now an array of arrays, where each inner array represents a row in the CSV file
csv_data.each do |row|
  puts row.inspect
end
445 chars
16 lines

In both cases, you can pass additional options as a hash to customize the behavior of the CSV class. For example, you can specify the delimiter character, the quote character, and the encoding. You can find more information on the available options in the official documentation.

gistlibby LogSnag