ruby系列教材(15):Class Methods

来源:百度文库 编辑:神马文学网 时间:2024/07/08 10:33:45
Class Methods:work without being tied to any particular object.
使用举例:
class Example
def instance_method              # instance method
end
def Example.class_method     # class method
end
end
定义是用 类名+方法名,应用的例子:
class SongList
MAX_TIME = 5*60                              # 5 minutes,常量,大写,使用下划线分割,我们现在见到的除了类名其他都用下滑线分隔
def SongList.is_too_long(song)
return song.duration > MAX_TIME    # return可以去掉,return 返回true or false,这个表达式会赋值给一个临时变量
end
end
song1 = Song.new("Bicylops", "Fleck", 260)
SongList.is_too_long(song1)→false
song2 = Song.new("The Calling", "Santana", 468)
SongList.is_too_long(song2)→true