Created
February 20, 2025 01:56
-
-
Save kigster/fd8d61d1377ab64dcfb4ec9590ad39fd to your computer and use it in GitHub Desktop.
Ruby Modules and method precedence explained
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module A | |
def foo | |
"A" | |
end | |
end | |
module Z | |
include A | |
def foo | |
"Z" | |
end | |
end | |
class B | |
include A | |
def foo | |
'B' | |
end | |
end | |
class C < B | |
include A | |
end | |
class D < C | |
prepend Z | |
end | |
puts "C.ancestors: #{C.ancestors}" | |
puts "B.ancestors: #{B.ancestors}" | |
puts "D.ancestors: #{D.ancestors}" | |
puts "C.foo=#{C.new.foo}" | |
puts "B.foo=#{B.new.foo}" | |
puts "D.foo=#{D.new.foo}" | |
# output | |
# C.ancestors: [C, B, A, Object, Kernel, BasicObject] | |
# B.ancestors: [B, A, Object, Kernel, BasicObject] | |
# D.ancestors: [Z, A, D, C, B, A, Object, Kernel, BasicObject] | |
# C.foo=B | |
# B.foo=B | |
# D.foo=Z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment