classMyClassdefmethod1# default is 'public'#...endprotected# subsequent methods will be 'protected'defmethod2# will be 'protected'#... endprivate# subsequent methods will be 'private'defmethod3# will be 'private'#...endpublic# subsequent methods will be 'public'defmethod4# will be 'public'#...endend
统一申明访问控制的例子:
1
2
3
4
5
6
7
8
9
10
11
class MyClass
def method1
end
def method2
end
# ... and so on
public :method1, :method4
protected :method2
private :method3
end
继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classParentdefsay_helloputs"Hello from #{self}"endendp=Parent.newp.say_hello# Subclass the parent...classChild<Parentendc=Child.newc.say_helloproduces:
Hellofrom#<Parent:0x007fb87110fd98>Hellofrom#<Child:0x007fb87110fac8>
However, you can include a module within a class definition.
When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses.
moduleDebugdefwho_am_i?"#{self.class.name} (id: #{self.object_id}): #{self.name}"endendclassPhonographincludeDebugattr_reader:namedefinitialize(name)@name=nameend# ...endclassEightTrackincludeDebugattr_reader:namedefinitialize(name)@name=nameend# ...endph=Phonograph.new("West End Blues")et=EightTrack.new("Surrealistic Pillow")ph.who_am_i?# => "Phonograph (id: 70266478767560): West End Blues"et.who_am_i?# => "EightTrack (id: 70266478767520): Surrealistic Pillow"
示例,使用系统的Enumerable Module,前提是实现 each 方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# tut_modules/vowel_finder.rbclassVowelFinder# 找出所有元音字母includeEnumerabledefinitialize(string)@string=stringenddefeach@string.scan(/[aeiou]/)do|vowel|yieldvowelendendendvf=VowelFinder.new("the quick brown fox jumped")vf.inject(:+)# => "euiooue"