I’ve created a ruby C extension TestExt, successfully compiled it, but when I try and use it in irb I can only access it’s methods after i’ve called include TestExt.
I’m testing it like this:
c:/test>irb -I lib
irb(main):001:0> require 'TestExt'
=> true
irb(main):002:0> TestExt.hello()
NoMethodError: undefined method `hello' for TestExt:Module
from (irb):2
from C:/Ruby192/bin/irb:12:in `<main>'
irb(main):003:0> TestExt.instance_methods
=> [:hello]
irb(main):004:0> include TestExt
=> Object
irb(main):005:0> TestExt.hello()
=> 0
irb(main):006:0> hello()
=> 0
Do you always have to include an extension? Is there an alternative way of includeing that doesn’t make the method hello global? Why can I see hello in the TestExt.instance_methods but not access it?
As you say yourself in your question,
hellois an instance method, ergo you first need to mix your module into something, so that you have an instance to call it on.When you
includea mixin at the top-level, that is basically equivalent towhich mixes
TestExtintoObjectand thus makeshelloavailable as an instance method of theObjectclass. Since everything inherits fromObject, includingModule, this makes thehelloinstance method available to both yourTestExtmodule and the anonymousmainobject (which is whatselfevaluates to at the top-level).Try
''.hello, and it will work also, since you mixedTestExtintoObjectandStringinherits fromObject.No.
Yes: just don’t
includeit in the global scope.Because it’s an instance method.