User Program Communication

Write to File in Ruby

Used to write to a file.


Syntax
output_file = open(file_name, 'w') #creating the file object

#can be done as many times as needed, no newline added automatically
output_file.write(content)
output_file.write("\n")

output_file.close 

Notes

When opening the file, 'w' specifies write mode.

The base path is the path of the source file.


Example
sc_funfacts = File.open('syntaxcenter_funfacts.txt', 'w')

sc_funfacts.write("Did you know that SyntaxCenters framework is Ruby on Rails?")
sc_funfacts.write("\n")
sc_funfacts.write("Actually, learning Ruby on Rails was one of the motivations behind this project!")
sc_funfacts.write("\n")

sc_funfacts.close

See Also
Documentation

RubyDocs - File API

Add to Slack

< Read from Text File   |   Local Variable Declaration >

© 2018 SyntaxDB. All Rights Reserved.