# Mixins and variables

**URL:** <https://www.ruby-forum.com/t/mixins-and-variables/49644>\
**Category:** Ruby\
**Created:** [December 7, 2005, 6:10am UTC](https://www.ruby-forum.com/t/mixins-and-variables/49644 "2005-12-07T06:10:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![johannes.friestad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19adc/32.png) [@johannes.friestad](https://www.ruby-forum.com/u/johannes.friestad)\
**Post date:** [December 7, 2005, 6:10am UTC](https://www.ruby-forum.com/t/mixins-and-variables/49644/1 "2005-12-07T06:10:17Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![johannes.friestad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e19adc/32.png) [@johannes.friestad](https://www.ruby-forum.com/u/johannes.friestad)\
**Post date:** [December 7, 2005, 3:33pm UTC](https://www.ruby-forum.com/t/mixins-and-variables/49644/2 "2005-12-07T15:33:21Z")

</div>

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
