Challenge - 5 Problems
CSV Ruby Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
Look at how CSV.parse with headers:true lets you access columns by name.
✗ Incorrect
The CSV.parse method with headers:true treats the first line as headers. Each row is a CSV::Row object, so row['name'] and row['age'] access the values by column name. The code prints each person's name and age in the given format.
❓ Predict Output
intermediate2: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(',')
Attempts:
2 left
💡 Hint
Remember to convert string values to integers before multiplying.
✗ Incorrect
The code parses CSV with headers, extracts the 'value' column as strings, converts them to integers, doubles them, and prints them joined by commas.
🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Check the type of row when headers option is not set.
✗ Incorrect
Without headers:true, CSV.parse yields each row as an Array, not a CSV::Row. Arrays do not support string keys, so row['name'] raises a TypeError.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
Only CSV.parse with headers:true yields rows with string keys.
✗ Incorrect
Option D uses CSV.parse with headers:true, so each row is a CSV::Row and supports row['age']. Option D lacks headers:true, so row is an Array. Option D is invalid because CSV.read does not take a block. Option D expects a filename, not CSV text.
🚀 Application
expert2: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
Attempts:
2 left
💡 Hint
Headers are not counted as rows.
✗ Incorrect
The CSV string has one header row and three data rows. CSV.parse with headers:true returns only the data rows, so rows.size is 3.