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 #<Level1:0x23d5e8 @var1=“var1
set.”> (NoMethodError)
I’m running version 1.8.0 preview3 on OS X.
Donglai
I’m having trouble accessing instance variables directly. What’s wrong
with this…
[snip]
var1 set.
test.rb:13: undefined method `var1’ for #<Level1:0x23d5e8 @var1=“var1
set.”> (NoMethodError)
Try this (untestted)… does it work ?
class Level1
def initialize
@var1=‘var1 set.’
end
attr_reader :var1
def printvar1
@var1
end
end
l1=Level1.new
print l1.printvar1, “\n”
print l1.var1
···
On Tue, 01 Jul 2003 06:36:15 +0900, Donglai Gong wrote:
–
Simon Strandgaard
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 #<Level1:0x23d5e8 @var1=“var1
set.”> (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
4ddod3dddn1-89danrn10-dan3+ann6dan2an13dn1+dn2-dn3+5ddan2/9+an13nap