类的基本知识:
1.类的定义和对象的初始化:
点击(此处)折叠或打开
- class Song
- def initialize(name,artist,duration)
- @name=name
- @artist=artist
- @duration=duration
- end
- end
@开头的变量称为实例变量,对象中的所有方法均可访问实例对象。
点击(此处)折叠或打开
- song1=Song.new("Need you now","Carlz",300)
- song1.inspect ->"#"
inspect方法可以对象的ID号和实例变量打印出来;
还有另一种更好的格式化输出方法:to_s (类似于PHP中打印的to_string方法),但是默认的to_s方法只会返回对象的ID号,需要对它进行重写:
点击(此处)折叠或打开
- class Song
- def to_s
- "Song:#@name--#@artist (#@duration)"
- end
- end
点击(此处)折叠或打开
- song1.to_s -> "Song:Need you now--Carlz (300)"
2.类的继承和属性:
点击(此处)折叠或打开
- class KaraokeSong < Song
- def initialize(name,artist,duration,lyrics)
- super(name,artist,duration)
- @lyrics=lyrics
- end
- end
super关键字表明子类从超类(父类)中继承了相应的实例变量;
Ruby解释器检查对象方法调用时,先看该类中是否有该方法。否则,会去超类中找同名的方法,然后是超超类,依次追溯整个祖先链;
点击(此处)折叠或打开
- song2=KaraokeSong.new("My Way","Sinatra",225,"And now, the...")
- song2.to_s -> "Song:My Way--Sinatra (225)"
点击(此处)折叠或打开
- class KaraokeSong < Song
- def to_s
- super + {#@lyrics}
- end
- end
song2.to_s -> "Song:My Way--Sinatra (225) {And now, the...}"
对象和属性
可以通过attr_reader直接读取对象中实例变量,其原理是在类中动态的加入实例方法体,能够直接调用得到属性值
attr_reader :na, :art, :dur 会在类中生成方法名依次为"na,art,dur"的方法,这些方法会返回相应实例变量的属性值
点击(此处)折叠或打开
- class Song
- def initialize(name,artist,duration)
- @na=name
- @art=artist
- @dur=duration
- end
- attr_reader :na, :art, :dur
- end
- song1=Song.new("Need you now","Carlz",300)
- song1.dur -> 300
- song1.art -> Carlz
- song1.na -> Need you now