第五章 用类组织对象
重定义方法
class C
def m
puts "..."
end
def m
puts "........"
end
end
以第2次定义的方法为准
重新打开类
class C
def x
end
end
class C
def y
end
end
与下面代码等价
class C
def x
end
def y
end
end
可以将单个类的代码分散到多个文件中或者一个文件中的多个位置
实例变量和对象状态&初始化对象状态(initialize)
class Ticket
def initialize(venue,date)
@venue = venue
@date = date
end
def venue
@venue
end
def date
@date
end
end
这时,如果这样调用
th = Ticket.new("Town Hail","11/12/13")
cc = Ticket.new("Convention Center","12/13/14")
puts "We've created two tickets."
puts "The first is for a #{th.venue} event on #{th.date}."
puts "The second is for an event on #{cc.date}at #{cc.venue}."
输出结果如下:
We've created two tickets.
The first is for a Town Hall event on 11/12/13.
The second is for an event on 12/13/14 at Convention Center.
由于实例变量的作用,整个保存和检索对象信息的过程完成得很好。执行了initialize方法后,每个入场卷对象都有了自己的状态。
方法中的等号&语法糖衣
Ruby允许以等号结束的方法:
def price=(amount)
@price = amount
end
price=完成与set_price完全一样的工作。可以这样去调用它,等号后面的括号是可选的。
ticket.price=(65.00)
to_i(转换到整数)
y.to_i
split('/')分割字符串
month,day,year = date.splite('/')
实例方法属性
attr_reader :venue等效于
def venue
@venue
end
attr_writer :price等效于
def price(price)
@price = price
end
attr_accessor :price等效于
def price=(price)
@price = price
end
def price
@price
end
类方法&类的实例方法
类的实例方法引用方法如:
Ticket#price
类方法引用如:
Ticket.most_expensive
或
Ticket::most_expensive
注意,双引号是访问内建常量的方法,但在这里不是
常量
常量定义通常位于或靠近类定义的顶部
class Ticket
VENUES = ["Convention Center","Fairgrounds","Town Hail"]
调用:
puts Ticket::VENUES
常量使用双引号作为访问原则
常量可以重新赋值和改变,也可以给常量添加成员(使用<<方法)
例如,在文件routing.rb中有以下代码
Helpers = []
然后在稍后的某个地方有如下代码:
Helpers<< url_helper_name(name).to_sym
Helpers<< hash_access_name(name).to_sym
这段代码产生一个用于辅助方法名的数组,然后向其中插入这两个方法名。事实上只是在付与该名的对象中又添加了几项而已。
继承
如:
class Publication
attr_accessor :publisher
end
class Magazine < Publication
attr_accessor :editor
end
本文介绍Ruby语言中如何使用类来组织对象,包括方法重定义、实例变量与对象状态的管理、初始化方法initialize的使用,以及类方法和实例方法的区别。
187

被折叠的 条评论
为什么被折叠?



