实例变量和属性
类也可以有实例变量(在一些语言中也称为属性)。例如,由Rectangle类创建的对象应该都有一个高度和宽度。在Ruby中,实例变量不必显式地在类中声明,只是必须在它们的命名中以一个特殊字符来标记和使用。具体地说,所有的实例变量名都以"@"开头。为了实现当调用area方法时,存储矩形实例的高度和宽度,你仅需把实例变量添加到area方法即可:
class Rectangle
def area (hgt, wdth)
@height=hgt
@width = wdth
@height*@width
end
end |
更确切地说,当创建一个Rectangle实例时,应该指定高度和宽度,而实例变量在此时才确定。另外,Ruby提供了一种特殊的方法initialize,它允许你建立或准备类的新实例:
class Rectangle
def initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def area ()
@height*@width
end
end |
为了创建一个新的Rectangle对象或实例,你要调用标准的Ruby类构造器方法"new":
或,你可以使用没有括号的形式:
这个例子创建了一个新的Rectangle对象并且调用了initialize方法,其中传入参数4和7。注意,在下面的代码中添加了height和width方法以便共享高度和宽度信息:
class Rectangle
def initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def height
return @height
end
def width
return @width
end
def area ()
@height*@width
end
end |
同样,为了使另外某个方法能够更新或设置一个Rectangle对象的高度和宽度,需要定义其它一些设置方法:
class Rectangle
def initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def height
return @height
end
def height=(newHgt)
@height=newHgt
end
def width
return @width
end
def width=(newWdth)
@width=newWdth
end
def area ()
@height*@width
end
end |
译者注 本文中的mutator和accessor相当于其它语言中的setter和getter。
上面的mutator方法("height="和"width=")可能看起来有点神秘,但是它们确实只是一些方法。不要让命名中的等号蒙骗了你。在方法名最后的额外字符对于Ruby并不意味着什么,但是它提高了代码的可读性。请看下列代码:
在此,一个Rectangle对象的高度正被赋值(改变)。事实上,这仅是一个对Rectangle对象的"height="方法的调用。
因为授予到一个对象的实例变量的存取权限非常普通,所以Ruby提供了一组关键字来实现一次性定义实例变量和accessor/mutator方法,从而使这些实例变量成为"public"属性。这些关键字是attr_reader,attr_accessor。它们有助于极大地简化代码:
class Rectangle
attr_accessor :height, :width
def initialize (hgt, wdth)
@height = hgt
@width = wdth
end
def area ()
@height*@width
end
end |
在上面的示例代码中,attr_accessor给出了Rectangle相应于height和width属性的getter和setter。