Challenge 1: Write and Read a File — Solution File.open("diary.txt", "w") do |file| file.puts "Started learning Ruby today." file.puts "Exception handling makes a lot more sense now." file.puts "Excited for metaprogramming." end File.foreach("diary.txt").with_index(1) do |line, number| puts "#{number}: #{line.chomp}" end =begin Output: 1: Started learning Ruby today. 2: Exception handling makes a lot more sense now. 3: Excited for metaprogramming. Notes: - File.open("diary.txt", "w") with a block writes three lines and automatically closes the file once the block finishes, per the chapter's warning about always preferring the block form. - File.foreach("diary.txt") returns an Enumerator when chained with .with_index(1) (Chapter 4's Enumerator concept), pairing each line with a 1-based line number instead of the default 0-based index. - line.chomp strips the trailing newline each line carries after being read from the file, so the printed output doesn't have a blank line after every entry. =end