cattr_accessor 和 attr_accessor 区别

cattr_accessor是 Ruby on Rails ActiveSupport一部分,不像attr_accessorn是Ruby的语言特色.

cattr_accessor 是类级别上的attr_accessor,属于singleton方法。

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

他们字面上的的不同就是类变量和实例变量的getter/setter方法。

	@@class_count
	@instance_count

 

 

 

1 @@class_count
2 @instance_count

 

参考

posted on 2012-11-01 15:46  小浪鼓  阅读(406)  评论(0编辑  收藏  举报

导航