Created
January 12, 2011 19:34
-
-
Save hopsoft/776726 to your computer and use it in GitHub Desktop.
Pattern Dispatch - Illustrates how to invoke methods based on a convention or pattern
This file contains hidden or 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
| # setup a contrived class to demonstrate pattern dispatch | |
| class Person | |
| attr_accessor :first_name | |
| attr_accessor :last_name | |
| attr_accessor :pets_name | |
| attr_accessor :mothers_maiden_name | |
| def drag_queen_name | |
| "#{pets_name} #{mothers_maiden_name}" | |
| end | |
| end | |
| # construct an instance of the class | |
| person = Person.new | |
| person.first_name = "john" | |
| person.last_name = "doe" | |
| person.pets_name = "muffin" | |
| person.mothers_maiden_name = "brown" | |
| # use pattern dispatch to invoke all 'name' methods | |
| person.public_methods.each do |method_name| | |
| puts "#{method_name} = #{person.send(method_name)}" if method_name =~ /_name$/ | |
| end | |
| # -- output -- | |
| # first_name = john | |
| # last_name = doe | |
| # pets_name = muffin | |
| # mothers_maiden_name = brown | |
| # drag_queen_name = muffin brown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment