Ruby: attr_reader &attr_accessor用法
2016-07-04 10:26
399 查看
attr_reader 及attr_accessor主要是用来设置或读取类中的属性值.具体用法:
class Hello
attr_reader :msg
def initialize
@msg = "Hello, World"
end
def test
print @msg
end
end
h = Hello.new
h.test=>Hello, World
attr_reader 是只读,不能设置
而attr_accessor即可读取也可以设置
class Hello
attr_accessor :msg
def initialize
@msg = "Hello, World"
end
def test
print @msg
end
end
h.msg="hello,test"
h.test=> =>hello,test
注意:属性之针对实例变量即:带@的变量
class Hello
attr_reader :msg
def initialize
@msg = "Hello, World"
end
def test
print @msg
end
end
h = Hello.new
h.test=>Hello, World
attr_reader 是只读,不能设置
而attr_accessor即可读取也可以设置
class Hello
attr_accessor :msg
def initialize
@msg = "Hello, World"
end
def test
print @msg
end
end
h.msg="hello,test"
h.test=> =>hello,test
注意:属性之针对实例变量即:带@的变量
相关文章推荐
- Ruby学习_self
- 苹果系统升级OS X EL Capitan后cocoapod安装
- windows下搭建Ruby(基于eclipse的环境)开发环境
- windows下搭建Ruby(基于eclipse的环境)开发环境
- Ruby学习笔记
- Ruby on Rails 5.0 发布
- 一遍成功安装"Cocoapods"
- Ruby 开发工具
- Ubuntu 安装ruby on rails 环境
- Ruby实现二分搜索(二分查找)算法的简单示例
- Ruby元编程基础学习笔记整理
- Ruby元编程基础学习笔记整理
- ruby redo和retry的区别
- 浅析 Ruby 里的几个动态方法 (一),send 方法
- Ruby入门笔记
- Ruby入门笔记
- ruby文档
- ruby文档
- 翻译:Ralis5.0发布新闻稿
- Ruby FFI 入门教程