0
0
Rubyprogramming~20 mins

CSV library basics in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CSV Ruby Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby CSV code?
Consider this Ruby code using the CSV library. What will it print?
Ruby
require 'csv'
csv_text = "name,age\nAlice,30\nBob,25"
CSV.parse(csv_text, headers: true) do |row|
  puts "#{row['name']} is #{row['age']} years old"
end
AAlice,30\nBob,25
Bname is age years old\nAlice is 30 years old
CAlice is 30 years old\nBob is 25 years old
D30 is Alice years old\n25 is Bob years old
Attempts:
2 left
💡 Hint
Look at how CSV.parse with headers:true lets you access columns by name.
Predict Output
intermediate
2:00remaining
What does this Ruby CSV code output?
Given this Ruby code snippet, what will be printed?
Ruby
require 'csv'
csv_text = "id,value\n1,100\n2,200"
rows = CSV.parse(csv_text, headers: true).map { |r| r['value'].to_i * 2 }
puts rows.join(',')
A100,200
B200,400
Cid,value
D2,4
Attempts:
2 left
💡 Hint
Remember to convert string values to integers before multiplying.
🔧 Debug
advanced
2:00remaining
Why does this Ruby CSV code raise an error?
This Ruby code raises an error. What is the cause?
Ruby
require 'csv'
csv_text = "name,age\nAlice,30\nBob,25"
CSV.parse(csv_text) do |row|
  puts row['name']
end
Arow is an Array, so row['name'] raises TypeError
BCSV.parse requires headers:true to parse correctly
CThe CSV library is not required properly
DThe CSV text is malformed and missing commas
Attempts:
2 left
💡 Hint
Check the type of row when headers option is not set.
📝 Syntax
advanced
2:00remaining
Which option correctly reads CSV with headers and prints ages?
Choose the Ruby code snippet that correctly reads CSV text with headers and prints each age.
ACSV.foreach(csv_text) { |row| puts row['age'] }
BCSV.parse(csv_text) { |row| puts row['age'] }
CCSV.read(csv_text, headers: true) { |row| puts row['age'] }
DCSV.parse(csv_text, headers: true) { |row| puts row['age'] }
Attempts:
2 left
💡 Hint
Only CSV.parse with headers:true yields rows with string keys.
🚀 Application
expert
2:00remaining
How many rows are parsed from this CSV string?
Given this Ruby code, how many rows will be parsed and printed?
Ruby
require 'csv'
csv_text = "name,score\nJohn,85\nJane,90\nDoe,78"
rows = CSV.parse(csv_text, headers: true)
puts rows.size
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Headers are not counted as rows.