
If you want to just read the whole thing, you can do so with read. At any point, you can use the f.rewind method to go back to the beginning of the file. Readingīefore we get started, remember this: the way a file works, once a line has been read, it doens’t show up again you’re working your way through the file. Most of the time, you’ll be opening a file to read or write content from it, so let’s look at that functionality. So, what methods does an instance of File give you? Well, these methods actually come from the IO class, from which File inherits. ”a” : write-only (starts at the end of the file, if the file exists).“w+” : read and write (overwrites anything in the file, if the file exists).”w” : write-only (overwrites anything in the file, if the file exists).Most of the time, you’ll probably use these: You should also pass a second parameter, which decides how the file will be opened. Making instances of the File class works just the same as with Dir File.new returns a File object, while File.open can return it, or pass it to a block. If it’s not a directory, we can do whatever we want to. So, we’re saying, “skip to the next entry if the entry we currently have is a directory. The only part you aren’t familiar with is the next keyword, which skips the rest of the block and goes to the next iteration of it. That first line inside the block may confuse you a bit if you’re not used to Ruby, but look at it carefully. Relative paths will reference your current working directory, and paths prepended with will use the owner’s home directory. The each method passes the entries of directory one by one to the block. Generate Absolute File Path In Ruby - Today I Learned Generate Absolute File Path In Ruby Pass a string to File.expandpath to generate the path to that file or directory. This snippet opens the current directory and passes a block to the each method.
