Created
March 22, 2022 04:03
-
-
Save lucianghinda/3b67b597ab6805eeb796c5ccb13d654a to your computer and use it in GitHub Desktop.
Example of using include and extend in Ruby
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 WithInstanceMethod | |
def whoami | |
puts self.inspect | |
end | |
end | |
class One | |
include WithInstanceMethod | |
end | |
One.new.whoami # This will print an object id | |
puts One.instance_methods.include?(:whoami) # this will print true | |
puts One.methods.include?(:whoami) # this will print false | |
begin | |
One.whoami # This class method does not exists, it only exists as instance method | |
rescue NoMethodError => e | |
puts e | |
end | |
module WithClassMethod | |
def load | |
puts self.inspect | |
end | |
end | |
class Two | |
extend WithClassMethod | |
end | |
Two.load # This will print the class | |
puts Two.instance_methods.include?(:load) # this will print false | |
puts Two.methods.include?(:load) # this will print true | |
begin | |
Two.new.load # This instance method does not exists, it only exists as class method | |
rescue NoMethodError => e | |
puts e | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment