Created
May 5, 2012 22:25
-
-
Save thomd/2605966 to your computer and use it in GitHub Desktop.
ruby descendants method
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
# ruby1.9 | |
class Class | |
def descendants | |
ObjectSpace.each_object(::Class).select {|klass| klass < self } | |
end | |
end | |
# Ruby pre-1.8.7: | |
class Class | |
def descendants | |
result = [] | |
ObjectSpace.each_object(::Class) {|klass| result << klass if klass < self } | |
result | |
end | |
end | |
class Cat < Animal | |
end | |
class Dog < Animal | |
end | |
Animal.descendants # > [Cat, Dog] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment