Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
Created March 22, 2022 04:03
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 lucianghinda/3b67b597ab6805eeb796c5ccb13d654a to your computer and use it in GitHub Desktop.
Save lucianghinda/3b67b597ab6805eeb796c5ccb13d654a to your computer and use it in GitHub Desktop.
Example of using include and extend in Ruby
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