Skip to content

Instantly share code, notes, and snippets.

@kigster
Created February 20, 2025 01:56
Show Gist options
  • Save kigster/fd8d61d1377ab64dcfb4ec9590ad39fd to your computer and use it in GitHub Desktop.
Save kigster/fd8d61d1377ab64dcfb4ec9590ad39fd to your computer and use it in GitHub Desktop.
Ruby Modules and method precedence explained
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