Skip to content

Instantly share code, notes, and snippets.

@mkurtikov
Last active February 8, 2017 15:22
Show Gist options
  • Save mkurtikov/f42a4bd5c43f63e294bc4d84614f68ba to your computer and use it in GitHub Desktop.
Save mkurtikov/f42a4bd5c43f63e294bc4d84614f68ba to your computer and use it in GitHub Desktop.
Ruby Modules
module A
def self.a
p 'self a'
end
def a
p 'Aa'
end
def b
p 'Ab'
end
end
class B
include A
def a
p 'Ba'
end
end
B.new.a # Ba
B.new.b # Ab
A.a # self a
A.new # NoMethodError: undefined method `new' for A:Module
module A
module B
def self.nesting
Module.nesting
end
class C
def self.nesting
Module.nesting
end
end
end
end
A::B::C.new
A::B.nesting # [A::B, A]
A::B::C.nesting # [A::B::C, A::B, A]
# http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/
module A
def a
p 'a'
end
end
module B
def b
p 'b'
end
end
module C
def c
p 'c'
end
end
class E
#include A
end
class D
extend B
class << self
include C
end
end
E.a # NoMethodError: undefined method `a' for E:Class
E.new.a # a
D.b # b
D.new.b # NoMethodError: undefined method `b' for #<D:0x007f8ebc83f160>
D.c # c
D.new.c # NoMethodError: undefined method `c' for #<D:0x007f8ebb906b08>
@YuriyGolenko
Copy link

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