1. attr_accessor的用法相当简单, 就相当于getter和setter,看一个类就知道怎样用了:
- class Test
- attr_accessor :name
- def initialize()
- @name = "yanzilee9292"
- end
- end
- #test
- puts Test.new.name
保存这个类为test.rb文件, 通过命令行运行 ruby test.rb, 会得到以下结果:
yanzilee9292
2. 如果我们把attr_accessor去掉, 该怎么输出name的值呢
- class Test
- def initialize()
- @name ="yanzilee9292"
- end
- #test
- puts Test.new.instance_eval {@name}
- end
可以看到, 用attr_accessor会把事情变得更加简单
3. cattr_accessor和attr_accessor的区别
cattr_accessor就相当于java的类静态变量, 对所有的类实例共享
- class Counter
- cattr_accessor :class_count
- attr_accessor :instance_count
- end
- counter1 = Counter.new
- counter1.instance_count = 1
- counter1.class_count = 1
- counter2 = Counter.new
- p counter2.instance_count
- #> nil
- p counter2.class_count
- #> 1