Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %Q(=============================================================================
- Reading and Writing Text Files in Ruby - A Quick Tutorial
- presented by mjshi
- --------------------------------------------------------------------------------
- Making a file!
- --------------------------------------------------------------------------------
- f = File.new("file_name.txt", "w")
- Of course, you can have your own filename, and f can be anything!
- You just have to change everything else to match.
- So if I had
- a = File.new("boo.txt", "w")
- then my other commands would be
- a.write("BOO!")
- a.close
- --------------------------------------------------------------------------------
- Saving text into it!
- --------------------------------------------------------------------------------
- f.write("Hi there!")
- To make text appear on different lines, add a \n!
- f.write("Hi\nthere!")
- will make the text file look like this:
- Hi
- there!
- --------------------------------------------------------------------------------
- Closing the file
- --------------------------------------------------------------------------------
- Make sure to close the file after you're done with writing stuff into
- it so the file doesn't take up memory space.
- f.close
- Well, that was easy.
- --------------------------------------------------------------------------------
- Reading Text Files
- --------------------------------------------------------------------------------
- c = File.open("key.txt", &:gets) if File.exist?("key.txt")
- Now, let's translate this into common English!
- +-----------------------------------------------------------------------------
- | c =
- | Save the following stuff in c --
- |
- | File.open("key.txt", &:gets)
- | the strings of text inside the file named "key.txt"
- |
- | if File.exist?("key.txt")
- | if the file named "key.txt" can be found in the game root directory.
- +-----------------------------------------------------------------------------
- File.exist?("filename.txt") can actually also be used in a conditional
- branch's script section to check if the file is in that directory, and
- File.zero?("filename.txt") can also be used to check if the file is empty.
- --------------------------------------------------------------------------------
- Hope that was helpful!
- Now, go forth and break some 4th walls!
- ===============================================================================)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement