From: Anders Borch Date: 2003-07-01T06:04:27+09:00 Subject: Re: why can't I access my instance variables? Donglai Gong wrote: > I'm having trouble accessing instance variables directly. What's wrong > with this... > > class Level1 > def initialize > @var1='var1 set.' > end > > def printvar1 > @var1 > end > end > > l1=Level1.new > print l1.printvar1, "\n" > print l1.var1 > > I get the following output: > > % ruby test.rb > var1 set. > test.rb:13: undefined method `var1' for # (NoMethodError) > > I'm running version 1.8.0 preview3 on OS X. > > Donglai > > variables are private by default. You can write get and set methods to read and write their values. class Level1 def initialize @var1='var1 set.' end def printvar1 @var1 end def var1 @var1 # just return @val1 end def var1= (newval) # test the validity of newval here @val1 = newval end end if you feel lazy and have no need to have any tests in your accessor methods (get and set methods) then there is: class Foo attr_reader :readable_var attr_writer :writable_var attr_accessor :readable_and_writable_var end I hope this helps :) -- dc -e 4dd*od3*dddn1-89danrn10-dan3+ann6*dan*2*an13dn1+dn2-dn3+5*ddan2/9+an13nap