Last active
December 11, 2015 20:09
-
-
Save yangsu/4652955 to your computer and use it in GitHub Desktop.
Ruby Module Example
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
module Person | |
attr_accessor :name | |
def self.included(base) # included is invoked whenever a module is included; base is implicit | |
base.extend ClassMethods # extend will add the methods defined in ClassMethods as class methods | |
end | |
module ClassMethods | |
def can_speak | |
include InstanceMethods # This includes all the instance methods | |
end | |
end | |
module InstanceMethods | |
def speak | |
puts "I can talk, my name is #{@name}!" | |
end | |
end | |
def initialize(name) | |
@name = name | |
end | |
end | |
class Guy | |
include Person | |
can_speak | |
end | |
class ShyGuy | |
include Person | |
end | |
john = Guy.new('John') | |
bob = ShyGuy.new('Bob') | |
john.methods.include?(:speak) # true | |
bob.methods.include?(:speak) # false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment