Last active
December 11, 2015 20:08
-
-
Save yangsu/4652951 to your computer and use it in GitHub Desktop.
Ruby Inheritance/Macro 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
class Person | |
attr_accessor :name | |
def self.can_speak # This is a class method! Notice the self. | |
define_method 'speak' do # an instance method | |
puts "I can talk, my name is #{@name}!" | |
end | |
end | |
def initialize(name) | |
@name = name | |
end | |
end | |
class Guy < Person | |
can_speak | |
end | |
class ShyGuy < 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