Title here
Summary here
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:
File.open(...) do |f|
).Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the STDIN
and STDOUT
streams.