Last active
September 18, 2022 07:54
-
-
Save keithrbennett/5170777b33bf6a454978d6d7784f085a to your computer and use it in GitHub Desktop.
Shows that a module instance method will not overwrite a class instance method of the same name if `include` is used, but *will* if `prepend` is used.
This file contains 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
#!/usr/bin/env ruby | |
module M | |
def foo | |
puts 'I am a module instance method.' | |
end | |
end | |
# Class whose foo instance method is defined *after* the include. | |
class C1 | |
include M | |
def foo | |
puts 'I am a class instance method.' | |
end | |
end | |
# Class whose foo instance method is defined *before* the include. | |
class C2 | |
def foo | |
puts 'I am a class instance method.' | |
end | |
include M | |
end | |
# Class whose foo instance method is defined *after* the include. | |
class C3 | |
prepend M | |
def foo | |
puts 'I am a class instance method.' | |
end | |
end | |
# Class whose foo instance method is defined *before* the include. | |
class C4 | |
def foo | |
puts 'I am a class instance method.' | |
end | |
prepend M | |
end | |
C1.new.foo #=> I am a class instance method. | |
C2.new.foo #=> I am a class instance method. | |
C3.new.foo #=> I am a module instance method. | |
C4.new.foo #=> I am a module instance method. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment