Skip to content

Instantly share code, notes, and snippets.

@stevecass
Created November 25, 2014 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevecass/d718290951618a52f9f4 to your computer and use it in GitHub Desktop.
Save stevecass/d718290951618a52f9f4 to your computer and use it in GitHub Desktop.
Ancestor chaining in ruby
module AAA
def abc
"abc in AAA"
end
def not_in_common
"not_in_common in AAA"
end
end
module BBB
def abc
"abc in BBB"
end
end
class TestClass
include AAA, BBB
end
class SeparateIncludes
include AAA
include BBB
end
t = TestClass.new
puts
puts "Ancestors of #{t.class} are #{t.class.ancestors}"
puts "TestClass#abc returns \"#{t.abc}\""
puts
puts "Includes on separate lines behave differently"
puts "SeparateIncludes ancestors: #{SeparateIncludes.ancestors}"
puts
puts "SeparateIncludes#abc returns \"#{SeparateIncludes.new.abc}\""
@stevecass
Copy link
Author

Output

Ancestors of TestClass are [TestClass, AAA, BBB, Object, Kernel, BasicObject]
TestClass#abc returns "abc in AAA"

Includes on separate lines behave differently
SeparateIncludes ancestors: [SeparateIncludes, BBB, AAA, Object, Kernel, BasicObject]

SeparateIncludes#abc returns "abc in BBB"

Method lookup proceeds up the ancestor chain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment