You have learned how to manage files & folders in Ruby using built-in methods like File.read & File.write. There are some extra file handling utilities you can get access to within the FileUtils module.įor example, you can compare files, touch a file (to update the last access & modification time), or copy files & directories with cp_r.ītw the “r” in cp_r stands for “recursive”. Using the Dir class it’s also possible to print the current working directory:Ĭreate a temporary directory with mktmpdir: Use this if you only want to search for directories: This one line of code will recursively list all files in Ruby, starting from the current directory: # All files containing "spec" in the name Using Dir.glob you can get a list of all the files that match a certain pattern. If you need the absolute path, make sure you expand it: File.expandpath (File. The current file may be accessed with a relative path. You can also get stats for a file, like file size, permissions, creation date, etc: File.dirname ( FILE) will give you the current file’s path. If you want to process a file one line at a time, you can use the foreach method.įile.foreach("users.txt") When you’re done working with a file you want to close it to free up memory & system resources.Īs an alternative to having to open & close the file, you can use the File.read method: If you’re working with a file that has multiple lines you can either split the file_data, or use the readlines method plus the chomp method to remove the new line characters. You can read the contents of the file in three ways.
0 Comments
Leave a Reply. |