Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Fundamental - Diferenças de "include" e "extend" na inclusão de módulos
module Numbers
def one
puts "1"
end
def two
puts "2"
end
end
module Ordinals
def first
puts "1st"
end
def second
puts "2nd"
end
end
class MyClass1
include Numbers
extend Ordinals
end
m1 = MyClass1.new
m1.one # => "1"
m1.two # => "2"
m1.first # => NoMethodError: undefined method `first' for #<MyClass1:0x035930>
m1.second # => NoMethodError: undefined method `second' for #<MyClass1:0x035930>
MyClass1.one # => NoMethodError: undefined method `one' for MyClass1:Class
MyClass1.two # => NoMethodError: undefined method `two' for MyClass1:Class
MyClass1.first # => "1st"
MyClass1.second # => "2nd"
class MyClass2
end
MyClass2.extend Ordinals
MyClass2.first # => "1st"
MyClass2.second # => "2nd"
m2 = MyClass2.new
m2.first # => NoMethodError: undefined method `first' for #<MyClass2:0x10402a8>
m2.second # => NoMethodError: undefined method `second' for #<MyClass2:0x10402a8>
MyClass2.include Ordinals # => NoMethodError: private method `include' called for MyClass2:Class
class MyClass3
end
m3 = MyClass3.new
m3.extend Ordinals
m3.first # => "1st"
m3.second # => "2nd"
MyClass3.first # => NoMethodError: undefined method `first' for MyClass3:Class
MyClass3.second # => NoMethodError: undefined method `second' for MyClass3:Class
MyClass3.new.first # => NoMethodError: undefined method `first' for #<MyClass3:0x1055f04>
MyClass3.new.second # => NoMethodError: undefined method `second' for #<MyClass3:0x105bf30>
class MyClass4
end
MyClass4.send(:include, Numbers)
m4 = MyClass4.new
m4.one # => "1"
m4.two # => "2"
MyClass4.one # => NoMethodError: undefined method `one' for MyClass4:Class
MyClass4.two # => NoMethodError: undefined method `two' for MyClass4:Class
@londerson
Copy link

londerson commented Aug 8, 2013

Muito legal esse Gist!

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