Created
August 12, 2012 04:09
-
-
Save willywos/3329664 to your computer and use it in GitHub Desktop.
Calling same method on different objects in ruby
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
# | |
# This is the base class | |
# for the classes below. | |
# Each class calls :register which | |
# saves its self into subclasses | |
# | |
# When the display method is called on | |
# the base class it loops through the collection | |
# insdie @@subclasses and if the instance method | |
# exists on that object it will be called. | |
# | |
class Section | |
@@subclasses = { } | |
def self.register name | |
@@subclasses[name] = self | |
end | |
def self.display | |
@@subclasses.map do |k,v| | |
# | |
#Since every class that inherits Section | |
#will have a display method because Section does. | |
#Passing false to instance methods will fix it for | |
#us so it does not look at the display method in Section | |
# | |
if v.instance_methods(false).include?(:display) | |
v.new.display | |
end | |
end | |
end | |
end | |
# | |
# Class contains a display method | |
# this method will be called but | |
# cowboy will not be. | |
# | |
class Answer < Section | |
register :answer | |
def display | |
puts "I am a answer" | |
end | |
def cowboy | |
puts "I'm a cowboy" | |
end | |
end | |
# | |
#Class contains a display method | |
#this method will be called but beerme | |
#will not be. | |
# | |
class Question < Section | |
register :question | |
def display | |
puts "I am a question." | |
end | |
def beerme | |
puts "Beer me" | |
end | |
end | |
# | |
#Class does not have a instance | |
#method called display. It will not | |
#be called. | |
# | |
class Nope < Section | |
register :nope | |
def aa_meeting | |
puts "I need help" | |
end | |
end | |
#Calling base class which | |
#will call all its subclasses | |
Section.display |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment