attr_reader 及attr_accessor主要是用来设置或读取类中的属性值.具体用法:
class Hello
attr_reader :msg
def initialize
@msg = "Hello,World"
end
def test
print @msg
end
end
class Hello
attr_accessor :msg
def initialize
@msg = "Hello, World"
end
def test
print @msg
end
end
h = Hello.new
h.test=>Hello, World
attr_reader 是只读,不能设置
而attr_accessor即可读取也可以设置
h.msg="hello,test"
h.test=> =>hello,test
注意:属性之针对实例变量即:带@的变量
转自:http://blog.sina.com.cn/s/blog_7833c8450100solx.html
转自:http://blog.sina.com.cn/s/blog_7833c8450100solx.html