So I am trying out mixins and some metaprogramming in ruby and can’t get this to work for me. I want it to print “Baboon”
module A
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def install_A
include InstanceMethods
end
end
module InstanceMethods
class B
def testB
#What goes here???
A.monkey
end
end
attr_accessor :monkey
def initialize()
@monkey = "baboon"
end
def test
b = B.new
puts b.testB
end
end
end
class Chimp
include A
install_A
end
c = Chimp.new
c.test
Bis its own self-contained class. It is not associated or connected with any of the other classes or modules except to say that an instance of classBhappens to be created inside ofInstanceMethods::test. Declaringclass Binside of the definition formodule InstanceMethodslimits the scope ofBsuch that it’s not visible outside ofInstanceMethods, but it doesn’t connectBandInstanceMethodsin any way.What you need is to make the module’s variable visible inside
B. You can implement aninitializemethod forBthat takes a parameter, andInstanceMethods::testcan useb = B.new(@monkey)to pass the value toB(make sureB::initializestores the value as an instance variable).