-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathoop_concepts.rb
66 lines (50 loc) · 1.04 KB
/
oop_concepts.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Encapsulation:
class Document
def initialize(name)
@name = name
end
def set_name(name)
@name = name
end
end
d = Document.new('name1')
d.set_name('name2')
# Polymorphism:
# single interface to entities of different types.
class Document
def print
raise NotImplementedError, 'You must implement the print method'
end
end
class XmlDocument < Document
def print
p 'Print from XmlDocument'
end
end
class HtmlDocument < Document
def print
p 'Print from HtmlDocument'
end
end
XmDocument.new.print # Print from XmlDocument
HtmlDocument.new.print # Print from HtmlDocument
class GenericParser
def parse(parser)
parser.print
end
end
parser = GenericParser.new
puts 'Using the XmlDocument'
parser.parse(XmlDocument.new)
puts 'Using the HtmlDocument'
parser.parse(HtmlDocument.new)
# Inheritance with callback
class Foo
def self.inherited(subclass)
puts "New subclass: #{subclass}"
end
end
class Bar < Foo
end
class Baz < Bar
end