Embed Directive in Ruby
Here’s the translation of the Go code to Ruby, formatted in Markdown suitable for Hugo:
Our example demonstrates how to embed files and folders into a Ruby program. While Ruby doesn’t have a direct equivalent to Go’s //go:embed
directive, we can achieve similar functionality using Ruby’s built-in methods.
To set up the files for this example, you can use the following shell commands:
Then run the Ruby script:
In this Ruby version, we use File.read
to read the contents of files into strings, and File.binread
to read into byte arrays. We use Dir.glob
to get a list of files matching a pattern, which is similar to the wildcard functionality in the Go example.
Note that Ruby doesn’t have a built-in way to embed files at compile time like Go does. The files are read at runtime in this Ruby example. If you need to distribute your Ruby program with embedded files, you might consider using a gem like bindata
or creating a custom solution to package the files with your script.
Ruby’s approach is more straightforward for simple file reading, but it doesn’t provide the same level of compile-time embedding that Go’s embed
package offers. However, for many use cases, this runtime file reading in Ruby is sufficient and easy to use.