Chapter 3 Classes, Objects and Variables
命名规范
以@开头的是instance variable
类名以大写字母开头,在这本书里用驼峰法命名,如BookInStock
变量名和方法名通常以小写字母开头,字母间用_隔开,如read_in_csv_data
Virtual Attributes
class BookInStock
attr_reader :isbn
attr_accessor :price
def initialize(isbn,price)
@isbn=isbn
@price=price
end
def price_in_cents
Integer(@price*100+0.5)
end
def price_in_cents=(cents)
@price =cents/100.0
end
#...
end
price_in_cents就是一个virtual instance variable
从这段话来看,attribute是描述了一个类对外部表现出来的状态,类的内部状态是实现的一部分,不应该直接暴露给用户(因此Ruby的所有instance variables都是私有的)。因此 attribute可以是虚的,即它不是直接反应了内部状态的值,而是对这些值的抽象。
访问其它类
require方法可以用来加载库中的文件
require_relative 用于加载与当前文件相关的文件,
关于加载当前目录下的文件,参见 http://ruby-china.org/topics/2376
Access Control
public protected private
Protected methods can be invoked only by objects of the defining class and its sub-calsses. Access is kept with the family.
Private methods cannot be called with an explicit receiver—the receiver is always the current object, aslo know as self. This means that private methods can be called only in the context of the current object; you can't invoke another object's private methods.
在Ruby中 “The only easy way to change an object's state in Ruby is by calling one of its method."即instance variable是不能直接访问的。
指定访问控制权限的方法
方法一:
class MyClass
def method1 #default is 'public'
#...
end
protected #subsequent methods will be 'protected'
def method2
#...
end
private #subsequent methods will be 'private'
def methods3
#...
end
public #subsequent methods will be 'public'
def method4
#...
end
end
方法二:
class MyClass
def method1
end
#... and so on
public :method1, :method4
protected :method2
private :method3
end
Variables
Ruby中所有的variable都是对象的引用。
person1 = "Tim"
person2 = person1
person3 =person1.dup #新建一个对象,和person1有相同的内容
person1[0]='J'
puts "person1 is #{person1}" #person1 is Jim
puts "person2 is #{person2}" #person2 is Jim
puts "person3 is #{person3}" #perons3 is Tim
person1.freeze # prevent modifications to the object
person2[0] = "K" #抛出一个RuntimeError exception
可以对比下C++和JAVA。在方法参数传递时, JAVA和Ruby传递的都是引用的值,不是对象的拷贝,但是JAVA 存在着基本类型,基本类型作参数时虽也是传值,但表现和引用类型不一致。而C++在传递对象时需要明确区分了按值传递和按引用传递。