Bird
0
0

You want to read a file and create a hash where keys are line numbers (starting at 1) and values are the lines without newline characters. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - File IO
You want to read a file and create a hash where keys are line numbers (starting at 1) and values are the lines without newline characters. Which code correctly does this?
AFile.readlines('file.txt').to_h { |line| [line, line.chomp] }
BFile.readlines('file.txt').each_with_index.to_h { |line, i| [i, line.strip] }
CHash[File.readlines('file.txt').map.with_index { |line, i| [i + 1, line.chomp] }]
DFile.readlines('file.txt').map { |line| [line.chomp, line] }.to_h
Step-by-Step Solution
Solution:
  1. Step 1: Understand mapping lines to line numbers

    Using map.with_index allows pairing each line with its index starting at 0.
  2. Step 2: Adjust index and remove newline

    Adding 1 to index for line numbers starting at 1, and using chomp removes newline.
  3. Step 3: Convert array of pairs to hash

    Hash[] converts array of key-value pairs into a hash.
  4. Final Answer:

    Hash[File.readlines('file.txt').map.with_index { |line, i| [i + 1, line.chomp] }] -> Option C
  5. Quick Check:

    Use map.with_index + chomp + Hash[] = D [OK]
Quick Trick: Use map.with_index and chomp to build line-numbered hash [OK]
Common Mistakes:
  • Using each_with_index.to_h incorrectly
  • Swapping keys and values in hash
  • Not removing newline characters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes