-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolymorphism.rb
64 lines (51 loc) · 1.26 KB
/
polymorphism.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
# Source: https://blog.appsignal.com/2022/05/25/an-introduction-to-polymorphism-in-ruby-on-rails.html
# Takeaways
# 1. One way of implementing Polymorphism in Ruby is via inheritance
# 2. A more practical way of implementing Polymorphism in Ruby is via duck-typing
# 1. One way of implementing Polymorphism in Ruby is via inheritance
puts '# 1. One way of implementing Polymorphism in Ruby is via inheritance'
class Instrument
def instrument_example
puts 'Saxophone'
end
end
class Stringed < Instrument
def instrument_example
puts 'Guitar'
end
end
class Percussion < Instrument
def instrument_example
puts 'Drums'
end
end
all_instruments = [Instrument.new, Stringed.new, Percussion.new]
all_instruments.each do |instrument|
instrument.instrument_example
end
# 2. A more practical way of implementing Polymorphism in Ruby is via duck-typing
puts "\n# 2. A more practical way of implementing Polymorphism in Ruby is via duck-typing"
class Guitar
def brand
'Gibson'
end
end
class Drums
def brand
'Pearl'
end
end
class Bass
def brand
'Fender'
end
end
class Keyboard
def brand
'Casio'
end
end
all_instruments = [Guitar.new, Drums.new, Bass.new, Keyboard.new]
all_instruments.each do |instrument|
puts instrument.brand
end