Mixins and variables

  • Thread starter Johannes Friestad
  • Start date
J

Johannes Friestad

Hi,
I'm new to Ruby, and trying to figure out how the inheritance/mixin works:
I can't figure out how to set an instance variable with a mixin method
from the object's initialize().

Example:
-----------------
module TestMod
def x
@x
end
def x=3D(arg)
@x=3Darg
end
end

class TestClass
include TestMod
def initialize
x=3D('alpha')
printf("x=3D%s\n", x)
end
end

irb(main)..>tmp=3DTestClass.new
x=3Dalpha # x is set inside constructor
=3D> #<TestClass:0x37d9520>
irb(main)..>tmp.x
=3D> nil # x is unset on the returned object
 
J

James Edward Gray II

Hi,
I'm new to Ruby, and trying to figure out how the inheritance/mixin
works:
I can't figure out how to set an instance variable with a mixin method
from the object's initialize().

I see you have your answer, so let me just make some general comments:
Example:
-----------------
module TestMod
def x
@x
end
def x=(arg)
@x=arg
end

You can replace the last six lines with:

attr_accessor :x
end

class TestClass
include TestMod
def initialize
x=('alpha')

self.x = 'alpha' # as discussed, or just @x = 'alpha'
printf("x=%s\n", x)

And we would usually write that as:

puts "x=#{x}"

Hope that gives you an idea or two.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top