When working with Ruby, understanding Input/Output (IO) operations is essential for interacting with files, databases, and other external sources of data. In this article, we will explore the basics of Ruby IO operations and how to effectively use them in your code.
To read from a file in Ruby, you first need to open the file using the File.open
method. Here's an example:
file = File.open("example.txt", "r")
Once the file is open, you can read its contents using the read
method. Here's how you can read the entire file:
content = file.read
puts content
After you have finished reading from the file, it is important to close it using the close
method to free up system resources:
file.close
To write to a file in Ruby, you can open the file in write mode using the File.open
method with the "w" flag. Here's an example:
file = File.open("output.txt", "w")
Once the file is open for writing, you can use the puts
method to write content to the file. Here's an example:
file.puts "Hello, World!"
After you have finished writing to the file, remember to close it using the close
method:
file.close
In Ruby, you can read input from the standard input (usually the keyboard) using the gets
method. Here's an example:
puts "Enter your name:"
name = gets.chomp
puts "Hello, #{name}!"
To output data to the standard output (usually the console), you can use the puts
method. Here's an example:
puts "Hello, World!"
Understanding Ruby IO operations is crucial for working with files, databases, and other external sources of data in your Ruby applications. By following the examples and guidelines in this article, you can effectively read from and write to files, as well as interact with standard input and output in your Ruby code.
© 2024 RailsInsights. All rights reserved.