Bird
Raised Fist0
Rubyprogramming~10 mins

CSV library basics in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - CSV library basics
Start
↓
Require CSV library
↓
Open or create CSV file
↓
Read or write rows
↓
Process each row
↓
Close file
↓
End
This flow shows how Ruby uses the CSV library to open a file, read or write rows, process them, and then close the file.
Execution Sample
Ruby
require 'csv'

CSV.open('data.csv', 'w') do |csv|
  csv << ['Name', 'Age']
  csv << ['Alice', 30]
end
This code creates a CSV file named 'data.csv' and writes two rows: a header and one data row.
Execution Table
StepActionCSV Object StateOutput/File Content
1Require CSV libraryCSV module loadedNo output
2Open 'data.csv' for writingCSV file opened, ready to writeFile created or emptied
3Write row ['Name', 'Age']CSV has 1 rowName,Age
4Write row ['Alice', 30]CSV has 2 rowsName,Age Alice,30
5Close file after block endsCSV file closedFile saved with 2 rows
6End of programNo active CSV fileFinal file content: Name,Age Alice,30
💡 CSV file closed after writing rows, program ends.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
csvnilCSV object open with 1 rowCSV object open with 2 rowsnil (closed)
Key Moments - 2 Insights
Why do we use a block with CSV.open instead of just opening the file?
Using a block ensures the CSV file is automatically closed after the block finishes, as shown in execution_table step 5.
What does the << operator do with the csv object?
It adds a new row to the CSV file, shown in steps 3 and 4 where rows are added to the file.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the CSV file content after step 3?
A"Name,Age "
B"Alice,30 "
C"Name,Age Alice,30 "
D"" (empty)
💡 Hint
Check the 'Output/File Content' column at step 3 in the execution_table.
At which step is the CSV file closed?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look for 'Close file' action in the execution_table.
If we add another csv << ['Bob', 25] after step 4, what will be the final file content?
A"Alice,30 Bob,25 "
B"Name,Age Bob,25 "
C"Name,Age Alice,30 Bob,25 "
D"Name,Age Alice,30 "
💡 Hint
Adding a row appends it to the CSV file content as shown in steps 3 and 4.
Concept Snapshot
require 'csv' to use CSV features
Use CSV.open(filename, mode) with a block to open file
Inside block, use csv << [row] to add rows
Block auto-closes file when done
Rows are arrays representing CSV lines
Full Transcript
This visual execution shows how Ruby's CSV library works. First, the CSV library is loaded. Then, the program opens a CSV file named 'data.csv' for writing. It writes a header row ['Name', 'Age'] and a data row ['Alice', 30]. Each row is added using the << operator on the csv object. After the block ends, the CSV file is automatically closed and saved. The variable 'csv' holds the CSV object while writing and becomes nil after closing. Key points include using a block to ensure the file closes safely and understanding that each << adds a new row. The execution table tracks each step, showing the file content growing line by line.

Practice

(1/5)
1. What does the Ruby CSV method CSV.foreach do?
easy
A. Reads a CSV file line by line, yielding each row as an array.
B. Writes data to a CSV file line by line.
C. Converts a CSV file into a hash with headers as keys.
D. Deletes a CSV file from the system.

Solution

  1. Step 1: Understand CSV.foreach purpose

    The method CSV.foreach is designed to read CSV files line by line.
  2. Step 2: Identify the output format

    Each line is yielded as an array of strings representing the cells in that row.
  3. Final Answer:

    Reads a CSV file line by line, yielding each row as an array. -> Option A
  4. Quick Check:

    CSV.foreach reads lines as arrays [OK]
Hint: Remember: foreach reads rows, open writes rows [OK]
Common Mistakes:
  • Confusing reading with writing methods
  • Thinking it returns a hash instead of an array
  • Assuming it deletes files
2. Which of the following is the correct syntax to open a CSV file for writing in Ruby?
easy
A. CSV.read('file.csv', 'w')
B. CSV.open('file.csv', 'r') do |csv| ... end
C. CSV.foreach('file.csv') do |csv| ... end
D. CSV.open('file.csv', 'w') do |csv| ... end

Solution

  1. Step 1: Identify mode for writing

    To write to a CSV file, the mode should be 'w' (write mode).
  2. Step 2: Match syntax with CSV.open

    The correct syntax is CSV.open('file.csv', 'w') do |csv| ... end to open for writing.
  3. Final Answer:

    CSV.open('file.csv', 'w') do |csv| ... end -> Option D
  4. Quick Check:

    Open with 'w' writes CSV [OK]
Hint: Use 'w' mode with CSV.open to write files [OK]
Common Mistakes:
  • Using 'r' mode which is for reading
  • Using CSV.foreach for writing
  • Using CSV.read with mode argument
3. What will be the output of this Ruby code?
require 'csv'
CSV.foreach('data.csv') do |row|
  puts row.inspect
end

Assuming data.csv contains:
name,age
Alice,30
Bob,25
medium
A. Error: CSV.foreach requires a block
B. ["name", "age"]\n["Alice", "30"]\n["Bob", "25"]
C. ["name,age"]\n["Alice,30"]\n["Bob,30"]
D. name,age\nAlice,30\nBob,25

Solution

  1. Step 1: Understand CSV.foreach behavior

    It reads each line and yields an array of strings split by commas.
  2. Step 2: Analyze puts row.inspect output

    Using puts row.inspect prints the array representation of each row.
  3. Final Answer:

    ["name", "age"]\n["Alice", "30"]\n["Bob", "25"] -> Option B
  4. Quick Check:

    CSV.foreach yields arrays, inspect shows arrays [OK]
Hint: CSV.foreach yields arrays; inspect shows array format [OK]
Common Mistakes:
  • Expecting raw CSV string output
  • Confusing puts with print
  • Missing block for CSV.foreach
4. Identify the error in this Ruby code snippet:
require 'csv'
CSV.open('output.csv', 'w') do |csv|
  csv << 'name,age'
  csv << ['Alice', 30]
end
medium
A. The first csv << should be an array, not a string.
B. Missing require statement for CSV library.
C. The file mode 'w' is invalid for CSV.open.
D. csv << cannot accept arrays.

Solution

  1. Step 1: Check CSV.open usage for writing rows

    CSV expects each row as an array of fields, not a single string.
  2. Step 2: Identify the incorrect row format

    The line csv << 'name,age' should be csv << ['name', 'age'] to write two columns.
  3. Final Answer:

    The first csv << should be an array, not a string. -> Option A
  4. Quick Check:

    CSV rows must be arrays [OK]
Hint: Write rows as arrays, not comma strings [OK]
Common Mistakes:
  • Passing a string instead of array for a row
  • Forgetting to require 'csv'
  • Using wrong file mode
5. You want to read a CSV file and create a hash where the first column is the key and the second column is the value. Which Ruby code correctly does this using the CSV library?
hard
A. hash = CSV.read('file.csv').to_h
B. hash = CSV.open('file.csv', 'w') { |csv| csv.to_h }
C. hash = {} CSV.foreach('file.csv') do |row| hash[row[0]] = row[1] end
D. hash = CSV.foreach('file.csv') { |row| row.to_h }

Solution

  1. Step 1: Understand CSV.foreach usage for reading

    CSV.foreach reads each row as an array, allowing manual hash construction.
  2. Step 2: Build hash from first and second columns

    Assigning hash[row[0]] = row[1] correctly maps keys to values.
  3. Final Answer:

    hash = {} CSV.foreach('file.csv') do |row| hash[row[0]] = row[1] end -> Option C
  4. Quick Check:

    foreach + manual hash build = correct [OK]
Hint: Use foreach and assign hash keys manually [OK]
Common Mistakes:
  • Using CSV.read.to_h which doesn't convert arrays to hash
  • Using CSV.open with 'w' mode for reading
  • Expecting row.to_h to work directly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard