Writing Files in Ruby

Here’s the translation of the Go code to Ruby, with explanations in Markdown format suitable for Hugo:

Writing files in Ruby follows similar patterns to the ones we saw earlier for reading.

```ruby
# To start, here's how to dump a string (or just bytes) into a file.
File.write('/tmp/dat1', "hello\nruby\n")

# For more granular writes, open a file for writing.
File.open('/tmp/dat2', 'w') do |f|
  # You can write strings as you'd expect.
  f.write("some\n")
  bytes_written = f.write("writes\n")
  puts "wrote #{bytes_written} bytes"

  # There's no need for explicit flushing in Ruby as it's done automatically,
  # but you can force it if needed:
  f.flush

  # Ruby's IO class provides buffered writers.
  f.write("buffered\n")
  puts "wrote #{f.pos} bytes"
end

Try running the file-writing code:

$ ruby writing-files.rb
wrote 7 bytes
wrote 18 bytes

Then check the contents of the written files:

$ cat /tmp/dat1
hello
ruby
$ cat /tmp/dat2
some
writes
buffered

In Ruby, file operations are more straightforward, and many low-level details are abstracted away. For example:

  1. There’s no need for explicit error checking as Ruby uses exceptions.
  2. File closing is handled automatically when using block form (File.open(...) do |f|).
  3. Buffering is handled internally by Ruby’s IO system.
  4. There’s no need for explicit type conversions between strings and byte arrays.

Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the STDIN and STDOUT streams.