This program first creates a CSV file named people.csv with two columns and two data rows. Then it reads the file and prints each person's name and city.
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
Step 1: Check CSV.open usage for writing rows
CSV expects each row as an array of fields, not a single string.
Step 2: Identify the incorrect row format
The line csv << 'name,age' should be csv << ['name', 'age'] to write two columns.
Final Answer:
The first csv << should be an array, not a string. -> Option A
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
Step 1: Understand CSV.foreach usage for reading
CSV.foreach reads each row as an array, allowing manual hash construction.
Step 2: Build hash from first and second columns
Assigning hash[row[0]] = row[1] correctly maps keys to values.
Final Answer:
hash = {}
CSV.foreach('file.csv') do |row|
hash[row[0]] = row[1]
end -> Option C
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 unknownstrongwhile earning +1 Grip toward your certificate.