This is a minimal example demonstrating how to use zig.rb as a dependency to create Ruby extensions written in Zig, following standard Ruby gem conventions.
- Dependency Management: Uses
zig.rbas a path dependency inbuild.zig.zon - Build Integration: Uses the
addRubyExtensionfunction fromzig.rb - Simple Extension: Implements a single module function
Example.add(a, b)that adds two integers - Standard Gem Structure: Follows Ruby gem conventions with proper directory layout
- Proper Extension Paths: Automatically installs compiled extension to
lib/example/ruby_version/using Ruby's API version (e.g.,3.3.0)
From the example directory:
zig buildThis will:
- Fetch the
zig_rbdependency from the parent directory - Build the extension with Ruby C API configuration
- Output
example.sotolib/example/ruby_version/(e.g.,lib/example/3.3.0/)
The build system automatically determines the Ruby API version from RbConfig::CONFIG['ruby_version'] and installs the extension to the appropriate path following gem conventions.
Run the test script:
ruby test/test_example.rbOr use Rake:
rake testThis example can be packaged and distributed as a RubyGem with the pre-compiled extension:
# Build the extension
zig build
# Build the gem (includes the compiled .so file)
gem build example.gemspec
# Install locally to test
gem install ./example-0.1.0.gem
# Test the installed gem
ruby -e "require 'example'; puts Example.add(10, 20)"Important: The gem ships with the pre-compiled .so file, not the source code. Users don't need Zig installed to use the gem. In the future, when build.zig.zon supports git references, the dependency will be properly resolved during development.
Or use the extension in your own Ruby code:
require_relative 'lib/example'
result = Example.add(10, 20)
puts result # => 30The extension defines a single module Example with one function add:
fn add(self: Value, a: Value, b: Value) Value {
_ = self;
const a_int = a.toInt(i64) catch 0;
const b_int = b.toInt(i64) catch 0;
const sum = a_int + b_int;
return Value.from(sum);
}The function:
- Takes two Ruby
Valuearguments (first argument is unused self) - Converts them to Zig integers
- Adds them together
- Returns the result as a Ruby
Value
- The extension name in
Init_example()must match the.sofilename - The
addRubyExtensionfunction handles all Ruby C API configuration - The
zig.rblibrary provides type-safe wrappers (Value,Module) for Ruby integration