Forum: Ruby Mixins and variables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
johannes.friestad (Guest)
on 2005-12-07 07:10
(Received via mailing list)
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=(arg)
    @x=arg
  end
end

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

irb(main)..>tmp=TestClass.new
x=alpha               # x is set inside constructor
=> #<TestClass:0x37d9520>
irb(main)..>tmp.x
=> nil                 # x is unset on the returned object
-----------------

Does anyone know why it doesn't work? What can I do instead?
James G. (Guest)
on 2005-12-07 16:33
(Received via mailing list)
On Dec 6, 2005, at 11:06 PM, Johannes F. wrote:

> 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}"

>   end
> end

Hope that gives you an idea or two.

James Edward G. II
This topic is locked and can not be replied to.