Introduction
File.read lets you open a file and get all its content as one string. This is useful when you want to work with the whole file at once.
content = File.read("filename.txt")text = File.read("notes.txt")data = File.read("/home/user/data.csv")content = File.read("example.txt", encoding: "UTF-8")
filename = "sample.txt" # Create a sample file with some text File.write(filename, "Hello, Ruby!\nThis is a test file.") # Read the entire content of the file content = File.read(filename) # Print the content puts content
File.read do when given a filename?File.read reads the whole file content at once, returning it as a string.File.readlines return arrays, but File.read returns a string of all content.data.txt in Ruby?example.txt contains the text "Hello\nWorld"?content = File.read('example.txt')
puts contentFile.read returns the entire file content as a string, including newline characters as actual newlines.puts prints the string and interprets newline characters, so it outputs two lines: Hello and World.content = File.read('missing.txt')
puts contentmissing.txt does not exist.File.read raises an exception (Errno::ENOENT).notes.txt safely, so your program does not crash if the file is missing. Which code snippet correctly does this?rescue after File.read catches exceptions and returns a fallback string if file is missing.Pass the test and this pattern moves unknown