mixins

M

mark rudolph

I am begining to work with Modules and mixins
and I would really appreciate some insight.

For reference:
module Z
CONST=15
@inst_var=16
def inst_method1
CONST
end
def inst_method2
@inst_var
end
end

class C
include Z
def test
puts "inst_method1 = #{inst_method1}"
puts "inst_method2 = #{inst_method2}"
end
end

o=C.new
puts "#{o.test}" # -> inst_method1 = 15
# -> inst_method2 =


Although both methods appear as methods of o,
only the first returns a value - why?
What is it about @inst_var of Z that will not allow
it to be accessible in o?


Thanks very much.
 
T

ts

m> module Z
m> CONST=15
m> @inst_var=16

this is an instance variable for the module Z (a module is an object and
can have instance variables).

m> def inst_method1
m> CONST
m> end
m> def inst_method2
m> @inst_var

this is an instance variable for a C object

m> end
m> end

m> class C
m> include Z

To see it another way

#!/usr/bin/ruby
class A
@inst_var = 'instance variable for A'

def initialize
@inst_var = 'instance variable for an instance of A'
end

def self.inst_var1
@inst_var
end

def inst_var2
@inst_var
end
end

puts A.inst_var1
puts A.new.inst_var2
moulon%

moulon% ./b.rb
instance variable for A
instance variable for an instance of A
moulon%
 
M

mark rudolph

ts said:
m> module Z
m> CONST=15
m> @inst_var=16

this is an instance variable for the module Z (a module is an object and
can have instance variables).

m> def inst_method1
m> CONST
m> end
m> def inst_method2
m> @inst_var

this is an instance variable for a C object

m> end
m> end

m> class C
m> include Z

To see it another way

#!/usr/bin/ruby
class A
@inst_var = 'instance variable for A'

def initialize
@inst_var = 'instance variable for an instance of A'
end

def self.inst_var1
@inst_var
end

def inst_var2
@inst_var
end
end

puts A.inst_var1
puts A.new.inst_var2
moulon%

moulon% ./b.rb
instance variable for A
instance variable for an instance of A
moulon%


Thanks ts,

after your reply and some further testing
I think I understand.


Mark
 

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,774
Messages
2,569,598
Members
45,145
Latest member
web3PRAgeency
Top