Ruby writing to a file example


















How to append text to a file with Ruby. A Ruby temporary file example. How to process every line in a text file with Ruby. How to open a file and read its contents using Ruby. Scala 3 opaque types: How to create meaningful type names. Checking the file have read permission. Checking the file have write permission.

Next Ruby Hash select method. Recommended Articles. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide.

Load Comments. What's New. Most popular in Ruby. More related articles in Ruby. Method How to install Ruby on Windows? Ruby truly is an interactive, interpreted language. Clearly the command line approach to execution is of limited use once you get beyond a few lines of Ruby script.

A much more common approach is to place the Ruby script in a file, and then pass that file to the Ruby interpreter to run. To try this, create a file called hello. Placing Ruby code into a file is obviously much easier and practical than using multiple -e command line options. Suppose, however, that we want to go one step further and be able to execute a Ruby based program simply by typing the name of the file containing the code, rather than prefixing it with the ruby command. This can be achieved on Linux or UNIX by placing a special line at the top of the script file informing the environment responsible for executing the program such as a Linux command shell where to look for the Ruby interpreter.

This special line consists of a ' ', a '! Firstly, you need to know where ruby is located on your system. Assuming it is already in your PATH environment variable you can use the which command to find it:. Clearly if you got the above output, there is a problem.

This is simply a matter of the script not having execute permission. This can easily be rectified by using the chmod command to add execute permission to our script:.

The Shebang approach outlined in the preceding chapter does not work on Windows. The only difference is that the puts statement goes to the next line after printing the contents, whereas with the print statement the cursor is positioned on the same line. Until now, you have been reading and writing to the standard input and output. Now, we will see how to play with actual data files.

You can create a File object using File. Finally, you can use File. You can use File. However, there is one difference in between File. The difference is that the File. Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. Read-write mode. Overwrites the existing file if the file exists.

If the file does not exist, creates a new file for reading and writing. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode.



0コメント

  • 1000 / 1000