0
0
Rubyprogramming~5 mins

File.write for writing in Ruby

Choose your learning style9 modes available
Introduction
File.write lets you save text or data directly into a file quickly and easily.
You want to save user input into a file.
You need to create a new file with some content.
You want to overwrite an existing file with new data.
You want to log messages or results into a file.
You want to save program output for later use.
Syntax
Ruby
File.write(filename, content, mode: "w")
filename is the name of the file you want to write to.
content is the text or data you want to save inside the file.
Examples
Writes the text "Hello, world!" into a file named hello.txt.
Ruby
File.write("hello.txt", "Hello, world!")
Saves the string "12345" into data.txt, creating the file if it doesn't exist.
Ruby
File.write("data.txt", "12345")
Adds the line "Error occurred" to the end of log.txt without erasing existing content.
Ruby
File.write("log.txt", "Error occurred\n", mode: "a")
Sample Program
This program writes the message "Hi there!" into a file named greeting.txt and then prints a confirmation.
Ruby
filename = "greeting.txt"
message = "Hi there!"
File.write(filename, message)
puts "Saved message to #{filename}"
OutputSuccess
Important Notes
File.write overwrites the file by default unless you use mode: "a" to append.
If the file does not exist, File.write creates it automatically.
Use \n for new lines inside strings.
Summary
File.write saves text directly into a file quickly.
It creates the file if it doesn't exist and overwrites by default.
You can append to a file by setting mode to "a".