Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to require the CSV library.
Ruby
require '[1]'
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'CSV' with uppercase letters.
Forgetting to require the library before using it.
✗ Incorrect
The CSV library is included by requiring 'csv'. This makes CSV methods available.
2fill in blank
mediumComplete the code to read a CSV file named 'data.csv' and print each row.
Ruby
CSV.foreach('data.csv') do |[1]| puts [1].inspect end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'file' which is the whole file, not a row.
Using 'csv' which is the library name, not the row variable.
✗ Incorrect
CSV.foreach reads each row and yields it to the block as 'row'.
3fill in blank
hardFix the error in the code to parse CSV data from a string.
Ruby
data = "name,age\nAlice,30\nBob,25" rows = CSV.[1](data) rows.each { |row| puts row[0] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using CSV.foreach which expects a filename.
Using CSV.read which also expects a file.
✗ Incorrect
CSV.parse reads CSV data from a string. CSV.foreach is for files.
4fill in blank
hardFill both blanks to create a hash from CSV rows with headers.
Ruby
CSV.foreach('data.csv', headers: true) do |[1]| person = [2].to_h puts person end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the block and inside the block.
Forgetting to convert the row to a hash.
✗ Incorrect
Each row is yielded as 'row'. Calling to_h converts it to a hash with headers as keys.
5fill in blank
hardFill all three blanks to write CSV data with headers.
Ruby
CSV.open('output.csv', 'w', write_headers: true, headers: [[1]]) do |csv| csv.[2]([[3]]) end
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'puts' instead of '<<' to add rows.
Not providing headers as strings.
Not passing row data as an array.
✗ Incorrect
Headers are given as an array of strings. To add a row, use the '<<' operator with an array of values.