#访问器(accessor)类似getter
#设置器(setter)
class Box
def initialize (w,h)
@width = w
@height = h
end
#accessor
def get_width #attr_reader:width #attr_accessor:width
@width
end
def get_height #attr_reader:height #attr_accessor:height
@height
end
#setter
def set_width=(value) #attr_writer:width
@width = value
end
def set_height=(value) #attr_writer:height
@height = value
end
end
box = Box.new(10,20)
x = box.get_width
y = box.get_height
puts "width = #{x}"
puts "height = #{y}"
box.set_width = 2222
puts "修改后的width = #{box.get_width}"
#类变量和类方法
class Box
@@count = 0
def initialize(w,h)
@w, @h = w,h
@@count += 1 #类变量,在类的所有实例中共享
end
def self.print_count #类方法,也可以写成: 类名.方法名
puts "count:#@@count"
end
end
box1 = Box.new(12,13)
box2 = Box.new(22,23)
Box.print_count #调用类方法:类名.方法名