mruby is an implementation of Ruby that’s designed to be lightweight & integrated with C. To get started, you can run a bit of Ruby code from inside C code.
“Hello World” with mruby looks like this:
- Set up a new project and include mruby as a submodule
- Write some C code that loads mruby and executes some Ruby code
- Compile the C code & run the resulting binary
You can find an example similar to this one on GitHub.
Start a project
Make a directory for your new project and enter it:
Clone mruby source and compile mruby:
1 2 3 4
(You need bison and Ruby to compile mruby, see the install guide for more information.)
You can check if compilation was successful by running
mirb (interactive mruby):
1 2 3 4 5
Write the program
Here’s the whole of
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Let’s break that down:
Include mruby & compiler. The mruby VM takes bytecode instructions. The compiler is used to turn a string of Ruby code into mruby bytecode.
mrb_load_stringhandles both steps: Parse & compile Ruby code, then execute with the mruby VM.
Make a mruby instance. Create an instance of the mruby VM. This object contains the state of the Ruby evnironment. Besides using it to execute code, you can inject values into the Ruby environment or call Ruby code from C.
Use mruby to execute code from string. As described above, in this case, the string will be turned into VM instructions first, then executed by mruby.
Compile & run
Compile your C application, referencing the necessary mruby files:
Then, execute the resulting binary:
You did it!
.rbinto mruby bytecode.
mrb_statefrom C with things like
- Call Ruby methods from C with
However, I don’t know of any English documentation for these things yet!