Skip to content

Instantly share code, notes, and snippets.

@yangsu
Last active December 11, 2015 20:08
Show Gist options
  • Save yangsu/4652951 to your computer and use it in GitHub Desktop.
Save yangsu/4652951 to your computer and use it in GitHub Desktop.
Ruby Inheritance/Macro Example
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