0
0
Rubyprogramming~10 mins

CSV library basics in Ruby - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to require the CSV library.

Ruby
require '[1]'
Drag options to blanks, or click blank then click option'
Anet/http
Bcsv
Cjson
Ddate
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'CSV' with uppercase letters.
Forgetting to require the library before using it.
2fill in blank
medium

Complete 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'
Aline
Bcsv
Cfile
Drow
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.
3fill in blank
hard

Fix 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'
Aparse
Bread
Copen
Dforeach
Attempts:
3 left
💡 Hint
Common Mistakes
Using CSV.foreach which expects a filename.
Using CSV.read which also expects a file.
4fill in blank
hard

Fill 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'
Arow
Bline
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.
5fill in blank
hard

Fill 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'
A"name", "age"
Bputs
C"Alice", 30
D <<
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.