Defining classes in modules with the Ruby C API

I am trying to define a class inside a module with the Ruby C API. However, as I saw this done all over the network, it does not seem to work for me. In particular, a top-level module is created, but the class cannot be found inside the module. Here is my C file:

#include <ruby.h> static VALUE mTree; static VALUE cNode; VALUE hello_world(VALUE klass) { return rb_str_new2("hello world"); } void Init_tree() { mTree = rb_define_module("Tree"); cNode = rb_define_class_under(mTree, "Node", rb_cObject); rb_define_method(cNode, "hello_world", hello_world, 0); } 

Here is my extconf.rb:

 require 'mkmf' create_makefile('tree') 

Here is my test script:

 require 'tree' puts Tree # => Tree puts Tree::Node # => uninitialized constant Tree::Node (NameError) 

Does anyone help?

+4
source share
2 answers

This is weird, your example works for me:

 โ†’ ruby extconf.rb creating Makefile โ†’ make linking shared-object tree.bundle โ†’ irb >> $:<<'.' => [...] >> require 'tree' => true >> Tree => Tree >> Tree.class => Module >> Tree::Node.class => Class >> Tree::Node.new.hello_world => "hello world" 
+1
source

Try the following:

 require_relative 'tree' 
0
source

Source: https://habr.com/ru/post/1395857/


All Articles