class A
attr_accessor :var_a
def initialize(a="a", b="b")
puts "==initialize=="
@var_a = a
@var_b = b
puts "var_a=#{var_a}"
puts "@var_a=#{@var_a}"
#puts "var_b=#{var_b}"#Error
puts "@var_b=#{@var_b}"
end
def modify(a="modify_a", b="modify_b")
puts "==modify=="
var_a = a
var_b = b
puts "var_a=#{var_a}"
puts "@var_a=#{@var_a}"
puts "var_b=#{var_b}"
puts "@var_b=#{@var_b}"
end
def out()
puts "@var_a=#{@var_a}"
puts "@var_b=#{@var_b}"
end
def modify_x(a="modify_a_x", b="modify_b_x")
@var_a = a
@var_b = b
puts "var_a=#{var_a}"
puts "@var_a=#{@var_a}"
#puts "var_b=#{var_b}"#Error
puts "@var_b=#{@var_b}"
end
end
test = A.new()
puts "[main]A.var_a=#{test.var_a}"
puts "\n\n\n"
test.modify()
puts "[main]A.var_a=#{test.var_a}"
puts "\n\n\n"
test.var_a = "out_modify_a"
test.out
puts "[main]A.var_a=#{test.var_a}"
puts "\n\n\n"
test.modify_x
puts "[main]A.var_a=#{test.var_a}"
结果如下:
==initialize==
var_a=a
@var_a=a
@var_b=b
[main]A.var_a=a
==modify==
var_a=modify_a
@var_a=a
var_b=modify_b
@var_b=b
[main]A.var_a=a
@var_a=out_modify_a
@var_b=b
[main]A.var_a=out_modify_a
var_a=modify_a_x
@var_a=modify_a_x
@var_b=modify_b_x
[main]A.var_a=modify_a_x
谁能解释下 modify 函数中 var_a 修改了,@var_a没有修改 modify_x 函数中@var_a修改了,var_a 也修改了
欢聚话说:attr_accessor,再类内部能 get,不能 set 而对于对象,既可以 get,也能 set 我的理解有问题没?