什么是一个存取器?
我们在前面已经讨论过实变量了,但却未过多的讨论.一个对象的实变量属于它的属性,也是它与其它来自同一个类的对象的一般区别.读写它的属性是重要的;这样做需要做一个叫着属性存取器(attribute accessors)的方法.我们将很快看到我们并不是总要明确地写出存取器方法,但现在先让我们了解所有的细节.存取器的两种类型是写(writer)和读(reader).
ruby> class Fruit
| def set_kind(k) # a writer
| @kind = k
| end
| def get_kind # a reader
| @kind
| end
| end
nil
ruby> f1 = Fruit.new
#<Fruit:0xfd7e7c8c>
ruby> f1.set_kind("peach") # use the writer
"peach"
ruby> f1.get_kind # use the reader
"peach"
ruby> f1 # inspect the object
#<Fruit:0xfd7e7c8c @kind="peach">
足够简单;我们可以存取关于我们搜索的水果种类的信息.但我们的方法名还有点儿牢骚.下面的这个更简洁,也更方便.
ruby> class Fruit
| def kind=(k)
| @kind = k
| end
| def kind
| @kind
| end
| end
nil
ruby> f2 = Fruit.new
#<Fruit:0xfd7e7c8c>
ruby> f2.kind = "banana"
"banana"
ruby> f2.kind
"banana"
inspect方法
一个小插曲.你已注意到当我们试着直接观察一个对象,就会出现一些像 #<anObject: 0x83678> 的东西.这只是个缺省的行为,我们可以自由地改变它.我们所要做的只是加一个名为 inspect 的方法.它会换一个更明了的描述对象的字符串,包括部分或全部的实变量.
ruby> class Fruit
| def inspect
| "a fruit of the " + @kind + " variety"
新闻热点
疑难解答